How to distinguish a field to a specific class using reflection in java?

I use reflection to put all of my class member variables of type Card into an ArrayList<Card> instance. How to finish this last part (see Commented line below)?

 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? 
+8
java reflection
source share
2 answers

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

You need to get the value first, and then you can say 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()) { 
+13
source share
 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); 
+4
source share

All Articles