Java Reflection 从字段中获取实例

标签 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 );
    }
}

我需要使用反射,因为我将它与注释一起使用。这只是一个“示例”,方法AppleList.add(Apple apple)实际上是通过从类中获取方法,然后调用它来调用的。

然后这样做,例如:method.invoke(appleList, field);

原因:java.lang.IllegalArgumentException:参数类型不匹配

*编辑* 这可能对正在寻找相同内容的人有所帮助。

如果类 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 类匹配的实例。
这就是为什么我想知道:“它会返回哪个 Apple?”

最佳答案

田地本身并不是苹果——它只是一 block 田地。因为它是一个实例 字段,所以您需要一个声明类的实例才能获取值。你想要:

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

...当然,在 apple 字段被填充之后,实例被称为 person

关于Java Reflection 从字段中获取实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12848479/

相关文章:

java - 最少调用 subArrayLeftShift 方法来排序数组(面试题)

java - 如何使用泛型函数存储类的每个变量的值?

java - 从封闭的成员类访问阴影字段 (Java)

c# - 在像 'config.cfg' 这样的文本文件中存储程序设置背后的逻辑是什么?

java - 如何修复在 OpenGL 中沿 x 或 y 轴旋转时奇怪的对象拉伸(stretch)?

java - Eclipse/STS 自动将 "new"更正为 "newEmail"

matlab - 获取 Matlab 处理事件或属性

java - Singleton:在构造函数中抛出异常

Java for 循环迭代

c# - 使用反射映射相似对象 : Object does not match target type