是否可以简单地将代码插入我无法编辑的其他类的方法中?
这是我无法编辑的示例类,因为我不是所有者
package me;
public class Test {
public Test() {
}
public void doSomething() {
System.out.println("im doing something...");
}
}
我想在我的类中有一个事件方法是
//should fire when Test.doSomething is called
public static void onDoSomethingEvent() {
}
我想添加 onDoSomethingEvent();测试中的 doSomething 方法。
Method method = Class.forName("me.Test").getDeclaredMethod("doSomething");
method.setAccessible(true);
//is there something in some lib or else like this?
//method.insert("Main.onDoSomethingEvent()");
```
最佳答案
另一种方法是您可以创建一个类来扩展该 Test 并以您自己的方式覆盖 doSomething()。
关于Java 8 是否有可能使用反射或其他方法在方法中插入代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59118697/