有没有办法从字段中获取实例?
这是一个示例代码:
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 类匹配的实例。
这就是为什么我想知道:“它将返回哪个苹果?”