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?
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");
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.
Java allows us to cast variables of one type to another as long as the casting happens between compatible data types.
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.
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()) {
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With