用Java替换静态引用的方法

我有一个像下面这样的类,只有一个返回String的方法,但我想修改它从另一个类返回的内容,而不是自己硬编码.

public class Name {
    public static String getName() {
        return "MyName";
    }
}

有没有办法做到这一点?我试过BCEL,但似乎没有改变返回值.

编辑:这是一个mod.我试图通过不修改它使它与现有代码完全无关.

谢谢.

最佳答案 你确定你尝试过BCEL吗?我创建了一个完整的示例
here.

JavaClass target;
try {
  target = Repository.lookupClass("Target");
} catch (final ClassNotFoundException ex) {
  throw new RuntimeException("unable to resolve Target", ex);
}
final ClassGen targetGen = new ClassGen(target);
final ConstantPoolGen pool = targetGen.getConstantPool();
final ConstantMethodref ref = (ConstantMethodref) pool.getConstant(
    pool.lookupMethodref("Name", "getName", "()Ljava/lang/String;"));
ref.setClassIndex(pool.lookupClass("Target"));
ref.setNameAndTypeIndex(pool.addNameAndType("$Name$getName", "()Ljava/lang/String;"));
final InstructionList code = new InstructionList();
final InstructionFactory factory = new InstructionFactory(targetGen, pool);
code.append(factory.createConstant("overriden-name"));
code.append(factory.createReturn(Type.STRING));
code.setPositions();
final MethodGen methodGen = new MethodGen(
    Constants.ACC_PRIVATE | Constants.ACC_SYNTHETIC | Constants.ACC_STATIC,
    Type.STRING, new Type[0], new String[0], "$Name$getName", "Target",
    code, pool);
methodGen.setMaxLocals(0);
methodGen.setMaxStack(1);
targetGen.addMethod(methodGen.getMethod());
try {
  targetGen.getJavaClass().dump("Target.class");
} catch (final IOException ex) {
  throw new RuntimeException("unable to save Target", ex);
}

06001

点赞