簡體   English   中英

如何使用反射定義動態的setter和getter?

[英]How to define dynamic setter and getter using reflection?

我從資源束中循環了一個類的字符串,字段名列表。 我創建一個對象,然后使用循環,我想為該對象設置值。 例如,對於對象

Foo f = new Foo();

使用參數param1,我有字符串“ param1”,我想以某種方式將“ set”連接起來,例如“ set” +“ param1”,然后將其應用於f實例,如下所示:

f.setparam1("value");

和吸氣劑一樣。 我知道反思會有所幫助,但我無法做到。 請幫忙。 謝謝!

你可以做這樣的事情。 您可以使此代碼更通用,以便將其用於循環字段:

Class aClass = f.getClass();
Class[] paramTypes = new Class[1];
paramTypes[0] = String.class; // get the actual param type

String methodName = "set" + fieldName; // fieldName String
Method m = null;
try {
    m = aClass.getMethod(methodName, paramTypes);
} catch (NoSuchMethodException nsme) {
    nsme.printStackTrace();
}

try {
    String result = (String) m.invoke(f, fieldValue); // field value
    System.out.println(result);
} catch (IllegalAccessException iae) {
    iae.printStackTrace();
} catch (InvocationTargetException ite) {
    ite.printStackTrace();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM