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

前端 未结 2 510
一生所求
一生所求 2021-01-04 03:19

I am using reflection to put all my class\'s member variables that are of type Card class into an ArrayList instance. How do I finish t

2条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-04 04:03

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

    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()) {
    

提交回复
热议问题