
[英]Java: Possibility to insert many objects into one method with one parameter using one line of code
[英]Java 8 Is there a simple possibility to insert code in a method using reflections ore something else?
是否有一种简单的可能性在我无法编辑的其他类的方法中插入代码?
这是我无法编辑的示例类,因为我不是所有者
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()");
```
不是我知道。 我认为这将是一个安全漏洞。 但是,如果您可以访问生成事件的内容,则可以执行以下操作:
class MyClass extends Test {
@Override doSomething() {
super.doSomething(); // to invoke super class method.
//your code here
}
}
现在添加一个MyClass
实例作为该事件的listener
器。
另一种方法是您可以创建一个类来扩展该Test并以您自己的方式覆盖doSomething() 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.