Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?
like image 292
ZakTaccardi Avatar asked Nov 18 '14 23:11

ZakTaccardi


People also ask

How do you reflect a class in Java?

In order to reflect a Java class, we first need to create an object of Class . And, using the object we can call various methods to get information about methods, fields, and constructors present in a class. class Dog {...} // create object of Class // to reflect the Dog class Class a = Class. forName("Dog");

How do you find the class object of associated class using reflection?

8. How to get the class object of associated class using Reflection? Explanation: forName(String className) returns the Class object associated with the class or interface with the given string name.

Can you cast a class to another class in Java?

Java allows us to cast variables of one type to another as long as the casting happens between compatible data types.

Is it good practice to use reflection in Java?

It's very bad because it ties your UI to your method names, which should be completely unrelated. Making an seemingly innocent change later on can have unexpected disastrous consequences. Using reflection is not a bad practice. Doing this sort of thing is a bad practice.


1 Answers

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()) {
like image 132
Thilo Avatar answered Sep 22 '22 04:09

Thilo