java reflection list_Java Reflection从Field获取实例

有没有办法从一个领域获得实例?

这是一个示例代码:

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 );

}

}

我需要使用Reflection,因为我正在使用它带注释.这只是一个“样本”,方法AppleList.add(Apple apple)实际上是通过从类中获取方法然后调用它来调用的.

并且这样做,如:method.invoke(appleList,field);

cause: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课程相匹配的实例.

这就是为什么我想知道:“苹果会回归哪个?”

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值