有没有办法从现场得到的实例?
下面是一个示例代码:
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
* 编辑 *这可能是人谁是寻找同样的事情有帮助。
如果类的人,有2级或更多苹果的变量:
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 );
让我觉得它会去得到它匹配苹果类的实例。
这就是为什么我在想:“这对苹果将返回”