替换Java中的静态引用方法 [英] Replacing statically referenced method in Java

查看:260
本文介绍了替换Java中的静态引用方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个如下所示的类,其方法只返回一个String,但我想修改它从另一个类返回的内容,而无需自己对其进行硬编码.

I have a class like below with a method that just returns a String, but I want to modify what it returns from another class, without hardcoding it myself.

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

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

Is there any way to do this? I tried BCEL but that didn't seem to change the return value.

这是针对mod的.我试图通过不对其进行修改,使其完全独立于现有代码.

This is for a mod. I'm trying to make it completely independant from the existing code, by not modifying it.

谢谢.

推荐答案

您确定要尝试过BCEL吗?我在此处创建了一个可以正常工作的示例.

Are you sure you've tried BCEL? I created a fully-working example 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);
}

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

这篇关于替换Java中的静态引用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆