Java反射:如何从一个字段获取实例

11

有没有办法从一个字段中获取实例?
以下是示例代码:

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?”

1个回答

15

该字段本身不是一个苹果 - 它只是一个字段。由于它是一个实例字段,您需要声明类的一个实例才能获取值。您需要:

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

当然,在实例被引用为person后,apple字段被填充之后。


哦,原来是这样...我可以问另一个问题吗?如果有多个Apple变量怎么办? - sam
2
不确定你想做什么,但如果你只是想获取所有类型为Apple的字段,你可能需要使用Class.getDeclaredFields()来获取所有字段,然后循环遍历这些字段以查看哪些是Apple类型的。 - Zeki
我明白了,一开始我以为只需要知道如何获取一个字段的实例就足够了,所以我的问题并不是很清楚。实际上,我正在制作一个从类中“构建”Swing GUI的类,因此它将获取所有组件,如JButton、JTextField等。所以我想知道它是否会像这样工作:JComponent jcomponent = (JComponent) field.get(ClassExtendedFromJFrame); 类似这样的东西(有点令人困惑)。我会继续尝试,并看看它会返回什么,我也会尝试循环解决方案,感谢您的帮助。 - sam

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接