Java 8 是否有一种简单的可能性,使用反射或其他东西在方法中插入代码?



是否有一种简单的可能性,可以在我无法编辑的其他类的方法中插入代码?

这是我无法编辑的示例类,因为我不是所有者

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((添加到Test中的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()");
```

另一种方法是你可以创建一个类来扩展该测试并以你自己的方式覆盖doSomething((。

我不知道。 我认为这将是一个安全漏洞。 但是,如果您有权访问生成事件的内容,则可以执行以下操作:

class MyClass extends Test {
@Override doSomething() {
super.doSomething(); // to invoke super class method.
//your code here
}
}

现在添加MyClass的实例作为该事件的listener

最新更新