Java Reflection从一个字段中获取实例

时间:2012-10-11 21:03:30

标签: java reflection field instance

有没有办法从实地获取实例?
这是一个示例代码:

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 );

原因: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课程相匹配的实例 这就是为什么我想知道:“苹果会回归哪个?”

1 个答案:

答案 0 :(得分:11)

这个领域不是苹果本身 - 它只是一个领域。因为它是实例字段,所以在获得值之前需要声明类的实例。你想要:

Apple apple = (Apple) field.get(person);

...当apple字段为填充之后,当然为person提及的实例。