java 如何在java中使用反射将字段转换为特定类?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27006381/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 11:03:28  来源:igfitidea点击:

How to cast field to specific class using reflection in java?

javareflection

提问by ZakTaccardi

I am using reflection to put all my class's member variables that are of type Cardclass into an ArrayList<Card>instance. How do I finish this last part (see commented line below)?

我正在使用反射将类的所有类成员变量Card放入一个ArrayList<Card>实例中。我如何完成最后一部分(请参阅下面的注释行)?

ArrayList<Card> cardList = new ArrayList<Card>();
Field[] fields = this.getClass().getDeclaredFields();

for (Field field : fields) {
   if (field.getType() == Card.class) {
      //how do I convert 'field' to a 'Card' object and add it to the 'cardList' here?

回答by Thilo

Fieldis just the description of the field, it is not the value contained in there.

Field只是字段的描述,而不是其中包含的值。

You need to first get the value, and then you can cast it:

您需要先获取该值,然后才能对其进行转换:

Card x =  (Card) field.get(this);

Also, you probably want to allow subclasses as well, so you should do

此外,您可能还希望允许子类,因此您应该这样做

  //  if (field.getType() == Card.class) {

  if (Card.class.isAssignableFrom(field.getType()) {

回答by Mauro Midolo

ArrayList<Card> cardList = new ArrayList<Card>();
Field[] fields = this.getClass().getDeclaredFields();    

for (Field field : fields) {
   if (field.getType() == Card.class) {
      Card tmp = (Card) field.get(this);
      cardList.add(tmp);