java 通过反射向类添加新方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16485446/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Adding new method to a class through reflection
提问by Tapas Jena
Is it possible to add a method to a class through reflection in java??
是否可以通过java中的反射向类添加方法?
public class BaseDomain {
public BaseDomain(){
Field[] fields = this.getClass().getDeclaredFields();
for(int i=0; i<fields.length; i++){
String field = fields[i].toString();
String setterMethod = "public void set" + field.toLowerCase();
//Now I want to add this method to this class.
}
}
}
回答by Boris the Spider
No, not through reflection.
不,不是通过反思。
Reflection asks about classes and their members, you can change fields but you cannot create new ones. You cannot add new methods.
反射询问类及其成员,您可以更改字段但不能创建新字段。您不能添加新方法。
You can use a a bytecode manipulation libraryto add methods to classes; but why would you want to?
您可以使用字节码操作库向类添加方法;但你为什么要这样做?
You can't call the methods anyway except via reflection as they would obviously not exist at compile time.
除了通过反射之外,您无论如何都不能调用这些方法,因为它们在编译时显然不存在。
Maybe take a look at project Lombok- this is a annotation preprocessor that can add methods to classes at compile time. It will add getters and setters automagically as long as your classes are correctly annotated.
也许看看项目 Lombok- 这是一个注释预处理器,可以在编译时向类添加方法。只要您的类正确注释,它就会自动添加 getter 和 setter。
回答by Sri Harsha Chilakapati
No. You can't add methods through reflection. In this case, I'll use a scripting language like Beanshell 2. Here's a DynamicObject class
不。您不能通过反射添加方法。在这种情况下,我将使用像Beanshell 2这样的脚本语言。这是一个 DynamicObject 类
public class DynamicObject
{
bsh.Interpreter interpreter = null;
public DynamicObject()
{
interpreter = new bsh.Interpreter();
}
public void addToSource(String... method)
{
try
{
String main = "";
for (int i=0; i<lines.length; i++){
main += lines[i] + "\n";
}
interpreter.eval(main);
}
catch (Exception e)
{
e.printStackTrace();
}
}
public Object invoke(String methodname, Object... args)
{
try
{
return interpreter.getNameSpace().invokeMethod(methodname, args, bsh);
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
public Object invoke(String methodname)
{
return invoke(methodname, (Object[])null);
}
}
Now an example dynamic object will look like
现在一个示例动态对象看起来像
DynamicObject testObj = new DynamicObject();
testObj.addToSource(
"public int add ( int a, int b )",
"{",
"return a+b;",
"}"
);
int added = testObj.invoke( "add", 5, 4 ); // is 9