暴力访问是反射中用于访问private属性的,对于那些没法通过外部get set方法访问的属性,这时可以用暴力访问- import java.lang.reflect.Field;
-
- public class Test {
- public static void main(String []args) throws IllegalArgumentException, IllegalAccessException, SecurityException, NoSuchFieldException{
- PrivateObject privateObject = new PrivateObject("The Private Value");
-
- Field privateStringField = PrivateObject.class.
- getDeclaredField("privateString");
-
- privateStringField.setAccessible(true);
-
- String fieldValue = (String) privateStringField.get(privateObject);
- System.out.println("fieldValue = " + fieldValue);
- }
- }
复制代码 |