[英]Java Reflection get the Instance from a Field
有沒有辦法從一個領域獲得實例?
這是一個示例代碼:
public class Apple {
// ... a bunch of stuffs..
}
public class Person {
@MyAnnotation(value=123)
private Apple apple;
}
public class AppleList {
public add(Apple apple) {
//...
}
}
public class Main {
public static void main(String args[]) {
Person person = new Person();
Field field = person.getClass().getDeclaredField("apple");
// Do some random stuffs with the annotation ...
AppleList appleList = new AppleList();
// Now I want to add the "apple" instance into appleList, which I think
// that is inside of field.
appleList.add( .. . // how do I add it here? is it possible?
// I can't do .. .add( field );
// nor .add( (Apple) field );
}
}
我需要使用Reflection,因為我正在使用它帶注釋。 這只是一個“樣本”,方法AppleList.add(Apple apple)
實際上是通過從類中獲取方法然后調用它來調用的。
這樣做,如: method.invoke( appleList, field );
cause: java.lang.IllegalArgumentException: argument type mismatch
* 編輯 *這可能對正在尋找同樣事物的人有所幫助。
如果是Person類,則有2個或更多Apple變量:
public class Person {
private Apple appleOne;
private Apple appleTwo;
private Apple appleThree;
}
當我得到Field時,如:
Person person = new Person();
// populate person
Field field = person.getClass().getDeclaredField("appleTwo");
// and now I'm getting the instance...
Apple apple = (Apple) field.get( person );
// this will actually get me the instance "appleTwo"
// because of the field itself...
一開始, (Apple) field.get( person );
一行:( (Apple) field.get( person );
讓我覺得它會去找一個與Apple課程相匹配的實例。
這就是為什么我想知道:“蘋果會回歸哪個?”
這個領域不是蘋果本身 - 它只是一個領域。 因為它是一個實例字段,所以在獲得值之前需要一個聲明類的實例。 你要:
Apple apple = (Apple) field.get(person);
...當然, 填充 apple
字段用於被稱為person
的實例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.