问题描述
在普通Java中可以在运行时以编程方式覆盖类
的方法(甚至创建新方法)?
It is possible in plain Java to override a method of a classprogrammatically at runtime (or even create a new method)?
我想要即使我不在编译时知道这些类,也能够做到这一点。
I want to be able to do this even if I don't know the classes at compile time.
我的意思是在运行时重写:
What I mean exactly by overriding at runtime:
abstract class MyClass{
public void myMethod();
}
class Overrider extends MyClass{
@Override
public void myMethod(){}
}
class Injector{
public static void myMethod(){ // STATIC !!!
// do actual stuff
}
}
// some magic code goes here
Overrider altered = doMagic(
MyClass.class, Overrider.class, Injector.class);
现在,这个调用......
Now, this invocation...
altered.myMethod();
...会调用 Injector.myMethod()而不是 Overrider.myMethod()。
...would call Injector.myMethod() instead of Overrider.myMethod().
Injector.myMethod()是静态,因为在做了魔术之后
它是从不同的类实例(它是Overrider)调用的,
(所以我们阻止它访问本地字段)。
Injector.myMethod() is static, because, after doing "magic"it is invoked from different class instance (it's the Overrider),(so we prevent it from accessing local fields).
推荐答案
你可以使用像这样的东西来实时生成代码
You can use something like cglib for generating code on-the-fly
这篇关于Java反射:如何在运行时覆盖或生成方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!