Java反射从现场获取实例(Java Reflection get the Instance fro

2019-08-01 09: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

* 编辑 *这可能是人谁是寻找同样的事情有帮助。

如果类的人,有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 );
让我觉得它会去得到它匹配苹果类的实例。
这就是为什么我在想:“这对苹果将返回”

Answer 1:

该字段不是苹果本身 - 它只是一个领域。 因为它是一个实例字段,则需要申报类的实例之前,你可以得到一个值。 你要:

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

...后apple字段填充为实例化的简称是person ,当然。



文章来源: Java Reflection get the Instance from a Field