ZakTaccardi
ZakTaccardi

Reputation: 12467

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

I am using reflection to put all my class's member variables that are of type Card class into an ArrayList<Card> instance. How do I 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?

Upvotes: 20

Views: 29881

Answers (2)

Mauro Midolo
Mauro Midolo

Reputation: 1958

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

Upvotes: 6

Thilo
Thilo

Reputation: 262494

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

Upvotes: 30

Related Questions