[英]How can i get the `signature` field of java reflection Method object
[英]Java method to assign object field values with Reflection
我想知道是否有可能在 Java 中具有以下內容:
public class MyClass {
private String name;
private Integer age;
private Date dateOfBirth;
// constructors, getters, setters
public void setField(String aFieldName, Object aValue) {
Field aField = getClass().getDeclaredField(aFieldName);
// use: aField.set(...) with proper type handling
}
}
我真的被 setField 方法困住了,任何想法都會非常有幫助。
謝謝!
編輯:這樣做的原因是我想在另一個類中有一個方法,如下所示
public static MyClass setAll(List<String> fieldNames, List<Object> fieldValues) {
MyClass anObject = new MyClass();
// iterate fieldNames and fieldValues and set for each fieldName
// the corresponding field value
return anObject;
}
當然:
aField.set(this, aValue);
首先進行類型檢查:
if (!aField.getType().isInstance(aValue))
throw new IllegalArgumentException();
但是由於使用錯誤類型的值調用set
無論如何都會生成IllegalArgumentException
,因此這種檢查不是很有用。
雖然我不知道你為什么要這樣做(因為你已經有了 getter 和 setter),試試這個:
Field aField = getClass().getDeclaredField(aFieldName);
aField.set(this, aValue);
有關更多信息, 請參閱此。
我想建議一張map
而不是List<T>
。
for(Map.Entry<String,Object> entry:map.entrySet())
{
Field aField = anObject.getClass().getDeclaredField(entry.getKey());
if(entry.getValue().getClass().equals(aField.getType()))
aField.set(anObject,entry.getValue());
}
return anObject;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.