Import
1 | import java.lang.reflect.*; |
Get Class, Field and Method Objects
1 | Class<?> class = ClassforName("<className>""); |
Make private fields or methods accessible
1 | field.setAccessible(true); |
Read and write fields
1 | field.get(Object instance); // return the value(return type: Object) |
Invoke methods
1 | method.invoke(Object instance, Object... args); // return Object |
Modify final fields
1. Get the final field
1 | // First get the final field we want to modify |
2. Cancel the final bit
For general JVM
1 | Field modifiersField = Field.class.getDeclaredField("modifiers"); |
For Android
The member of Field representing modifiers is different. modifiers
-> accessFlags
1 | Field modifiersField = Field.class.getDeclaredField("accessFlags"); |
Reference
java.lang.Class
java.lang.reflect.Method
java.lang.reflect.Field
Java Reflection Tutorial