有没有办法从一个字段中获取实例?
以下是示例代码:
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 );
}
}
我需要使用反射,因为我正在使用它与注释一起。这只是一个“示例”,方法
AppleList.add(Apple apple)
实际上是通过从类中获取该方法,然后调用它来调用的。像这样操作:
method.invoke( appleList, field );
会导致:java.lang.IllegalArgumentException: argument type mismatch
*编辑*
对于寻找相同内容的人可能会有所帮助。如果Person类有2个或更多个Apple变量:
public class Person {
private Apple appleOne;
private Apple appleTwo;
private Apple appleThree;
}
当我获得字段时,例如:
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类匹配的实例。
这就是我想知道的:“它将返回哪个Apple?”