我有一个如下所示的类,其方法仅返回一个字符串,但我想修改它从另一个类返回的内容,而无需自己对其进行硬编码。
public class Name {
public static String getName() {
return "MyName";
}
}
有什么办法可以做到这一点吗?我尝试了 BCEL 但这似乎并没有改变返回值。
编辑:这是一个模组。我试图通过不修改它来使其完全独立于现有代码。
Thanks.
Are you sure你试过BCEL吗?我创建了一个完整的示例here http://pastie.org/private/p05jdjpxskuj2ede0jsm2w.
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);
}
C:\dev\scrap>javac Target.java
C:\dev\scrap>java Target
original-name
C:\dev\scrap>javac -cp .;bcel-6.0.jar Instrumenter.java
C:\dev\scrap>java -cp .;bcel-6.0.jar Instrumenter
C:\dev\scrap>java Target
overriden-name
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)