Java Reflection

Import

1
import java.lang.reflect.*;

Get Class, Field and Method Objects

1
2
3
4
Class<?> class = ClassforName("<className>"");
Field field = class.getDeclaredField("<field_name>");
Method method = class.getDeclaredMethod("<methodName>", Class<?>... parameterTypes)
// e.g. method = class.getDeclaredMethod("func", String.class, String.class);

Make private fields or methods accessible

1
2
field.setAccessible(true);
method.setAccessible(true);

Read and write fields

1
2
field.get(Object instance); // return the value(return type: Object)
field.set(Object instance, Object value);

Invoke methods

1
2
method.invoke(Object instance, Object... args); // return Object
// instance is null for static methods

Modify final fields

1. Get the final field

1
2
3
4
// First get the final field we want to modify
Class<?> class = ClassforName("<className>"");
Field the_final_field = class.getDeclaredField("<field_name>");
the_final_field.setAccessible(true);

2. Cancel the final bit

For general JVM

1
2
3
Field modifiersField = Field.class.getDeclaredField("modifiers");
modifiersField.setAccessible(true);
modifiersField.setInt(the_final_field, the_final_field.getModifiers() & ~Modifier.FINAL);

For Android

The member of Field representing modifiers is different. modifiers -> accessFlags

1
2
3
4
Field modifiersField = Field.class.getDeclaredField("accessFlags");
// the following code is the same
modifiersField.setAccessible(true);
modifiersField.setInt(the_final_field, the_final_field.getModifiers() & ~Modifier.FINAL);

Reference

java.lang.Class
java.lang.reflect.Method
java.lang.reflect.Field
Java Reflection Tutorial