Java Reflection从字段获取实例 [英] Java Reflection get the Instance from a Field
问题描述
是否可以从字段中获取实例?
这是示例代码:
is there any way to get the Instance from a Field?
Here's a sample code:
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)
并随后调用它来调用方法AppleList.add(Apple apple)
.
I need to use Reflection, because I'm using it with annotations. This is just a "sample", the method AppleList.add(Apple apple)
is actually called by getting the method from the class, and then invoking it.
并这样做,例如:method.invoke( appleList, field );
原因:java.lang.IllegalArgumentException: argument type mismatch
* EDIT * 这对于正在寻找同一事物的人可能会有所帮助.
*EDIT* This might be helpful for someone who's looking for the same thing.
如果Person类具有两个或多个Apple变量:
if the class Person, had 2 or more Apple variables:
public class Person {
private Apple appleOne;
private Apple appleTwo;
private Apple appleThree;
}
当我获得该字段时,例如:
when I get the Field, like:
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类匹配的实例.
这就是为什么我想知道:它将返回哪个苹果公司?"
at the beginning, by looking at the line alone: (Apple) field.get( person );
made me think that it would go and get an Instance which matches Apple class.
that's why I wondered: "which Apple will it return?"
推荐答案
该字段本身不是苹果,而是一个字段.由于它是一个 instance 字段,因此需要一个声明类的实例才能获取值.您想要:
The field isn't an apple itself - it's just a field. As it's an instance field, you need an instance of the declaring class before you can get a value. You want:
Apple apple = (Apple) field.get(person);
当然,对于 .... ... after the 这篇关于Java Reflection从字段获取实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!person
实例,在apple
field is populated for the instanced referred to be person
, of course.