Java 反射从字段中获取实例
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12848479/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java Reflection get the Instance from a Field
提问by sam
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 );
}
}
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.
我需要使用反射,因为我将它与注释一起使用。这只是一个“示例”,方法AppleList.add(Apple apple)
实际上是通过从类中获取方法,然后调用它来调用的。
and doing so, like: method.invoke( appleList, field );
并这样做,例如: method.invoke( appleList, field );
causes: java.lang.IllegalArgumentException: argument type mismatch
原因: java.lang.IllegalArgumentException: argument type mismatch
*EDIT*This might be helpful for someone who's looking for the same thing.
*编辑*这可能对正在寻找相同事物的人有所帮助。
if the class Person, had 2 or more Apple variables:
如果类 Person 有 2 个或更多 Apple 变量:
public class Person {
private Apple appleOne;
private Apple appleTwo;
private Apple appleThree;
}
when I get the Field, like:
当我拿到 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...
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?"
一开始,仅看一行:(Apple) field.get( person );
让我认为它会去获取一个与 Apple 类匹配的 Instance 。
这就是为什么我想知道:“它会返回哪个苹果?”
回答by Jon Skeet
The field isn't an apple itself - it's just a field. As it's an instancefield, you need an instance of the declaring class before you can get a value. You want:
田地本身不是苹果——它只是一块田地。由于它是一个实例字段,因此您需要声明类的实例才能获得值。你要:
Apple apple = (Apple) field.get(person);
... after the apple
field is populatedfor the instanced referred to be person
, of course.
...当然,在为所引用的实例填充该apple
字段之后。person