Java 向现有类动态添加getter和setter
有没有人建议我如何将getter和setter动态添加到现有类中?我需要创建同一类的实例以供进一步使用。我将在编译时使用Pojo类。在运行时读取属性文件并需要创建getter和setter这些实体时,您可以为其创建包装:Java 向现有类动态添加getter和setter,java,Java,有没有人建议我如何将getter和setter动态添加到现有类中?我需要创建同一类的实例以供进一步使用。我将在编译时使用Pojo类。在运行时读取属性文件并需要创建getter和setter这些实体时,您可以为其创建包装: public class MyWrapper extends TheClass { private TheClass theClass; //getter/setters } 如上所述不可能,因为不允许动态修改类 如果您可以使用现有类上的接口,那么可以使用J
public class MyWrapper extends TheClass {
private TheClass theClass;
//getter/setters
}
如上所述不可能,因为不允许动态修改类 如果您可以使用现有类上的接口,那么可以使用Java的动态代理支持来添加getter和setter
private static class InstanceProxy implements InvocationHandler {
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
String methodName = method.getName();
// Do logic based on method name
}
}
并使用创建一个代理
这些代理对象将为调用的方法提供一个给定的接口和动态逻辑。Java没有内置的方法来添加全新的方法。你可以试试嵌入式脚本引擎(http://docs.oracle.com/javase/6/docs/api/javax/script/package-summary.html),然后使用Javascript、jRuby、Groovy等。。这些语言将根据您的需要提供更多的运行时功能,并且应该能够与java代码交互。根据您的编辑,最好在POJO中有一个
映射,以便在运行时加载新的属性/值:
public class SomePojo {
private int intAttribute;
private String stringAttribute;
private Map<String, String> dynamicProperties = new HashMap<String, String>();
//getters and setters...
}
public class BLClass {
public static void loadProperties(Properties properties, SomePojo pojo) {
Enumeration<?> enumeration = properties.propertyNames();
while (enumeration.hasMoreElements()) {
String key = (String) enumeration.nextElement();
String value = properties.getProperty(key);
pojo.getDynamicProperties().put(key, value);
}
}
}
公共类SomePojo{
私有的不完整属性;
私有字符串属性;
私有映射dynamicProperties=newhashmap();
//接球手和接球手。。。
}
公共类{
公共静态void加载属性(属性属性,SomePojo pojo){
枚举=properties.propertyNames();
while(枚举.hasMoreElements()){
字符串键=(字符串)枚举.nextElement();
字符串值=properties.getProperty(键);
getDynamicProperties().put(键,值);
}
}
}
这是可以做到的。通常ORM工具也做类似的事情。它被称为字节码编织/字节码增强。您可以使用第三方字节码工程库(如BCEL)来完成它
试试谷歌搜索,这里有几个链接可以让你对这个话题有更多的了解
反射可用于设置/获取值。(注意性能影响。)在你的问题中添加一些细节。你所说的“动态”是什么意思?在不改变源代码的情况下?这有点难理解-您是否正在寻找一个工具来生成java代码(文本),包括getter、setter和constructor?我将在编译时使用Pojo类。在运行时读取属性文件,需要创建这些实体的getter和setter。这就像在运行时更新现有的类文件,为什么不能在编译时使用这些getter和setter呢?@user1805079不客气。由于您是新来的,请单击我的帖子=)旁边的绿色标记,将此帖子标记为答案。