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

前端 未结 2 512
一生所求
一生所求 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()) {
    
    0 讨论(0)
  • 2021-01-04 04:20
    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);
    
    0 讨论(0)
提交回复
热议问题