Reflection
What are some practical use case of Reflections?
Getting name fields:
import java.lang.reflect.Field;
public class Reflection {
public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
Cat myCat = new Cat("Fred", 3);
System.out.println("Initially");
System.out.println(myCat);
System.out.println("###########################");
// Iterating through all the fields by calling getDeclaredFields
Field[] fields = myCat.getClass().getDeclaredFields();
for(Field field: fields) {
// System.out.println(field.getName()); // Prints the field name
if(field.getName().equals("name")) {
field.set(myCat, "Mercury");
}
}
System.out.println("After setting name with reflection loop");
System.out.println(myCat);
System.out.println("###########################");
// Get a field name based on the given name
Field ageField = myCat.getClass().getDeclaredField("age");
ageField.set(myCat, 6);
System.out.println("After setting age with reflection getField");
System.out.println(myCat);
}
static class Cat {
private String name;
private int age;
public Cat(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Cat{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
}Output:
Invoking methods
Output
Usecases:
Issues with Reflection
Last updated