2012-11-07 26 views
0

任何一次都建議我如何動態地將getter和setter添加到現有的類?我需要創建相同類的實例以供進一步使用。我將在編譯時使用Pojo類。在運行時讀取屬性文件並需要創建getter和setter這些實體動態添加getter和setter到現有的類

+1

反射可以用來設置/獲取值。 (注意性能影響。)在您的問題中添加一些細節。 – Nishant

+0

「動態」是什麼意思?不改變源代碼? –

+0

這有點難以理解 - 您是否在尋找一種生成Java代碼(文本)的工具,包括getter,setter和構造函數? –

回答

0

你可以爲它創建一個包裝:

public class MyWrapper extends TheClass { 
    private TheClass theClass; 

    //getter/setters 
} 
0

不可能的,因爲規定,如動態修改類是不允許的。

如果您可以使用現有類的接口,您可以使用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.lang.reflect.Proxy.newProxyInstance代理。

這些代理對象將具有調用方法的給定接口和動態邏輯。

2

Java沒有內置手段來添加全新的方法。您可以嘗試使用嵌入式腳本引擎(http://docs.oracle.com/javase/6/docs/api/javax/script/package-summary.html),然後使用Javascript,jRuby,Groovy等。這些語言將允許更多的運行時功能沿着你所需要的方向發展,並且應該能夠與你的java代碼交互。

0

根據您的修改,這將是最好有一個Map<String, String>你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); 
     } 
    } 
} 
+0

謝謝Luiggi Mendoza – user1805079

+0

@ user1805079不客氣。既然你是新來的,請點擊我帖子旁邊的綠色標記,將此帖標記爲答案。 –

0

這是可以做到。通常ORM工具做類似的事情。它被稱爲字節碼編織/字節碼增強。您可以使用第三方字節代碼工程庫(如BCEL)來完成它。

嘗試使用谷歌搜索,這裏有幾個鏈接,可以讓你更深入的瞭解這個主題。

Bytecode Weaving
Bytecode Enhancement