Java的反射工具很強大,有句著名的話:No reflection ,no frameworks.
納整理一個小工具類:
/**
* @Author 落葉飛翔的蝸牛
* @Date 2018/3/10
* @Description
*/
public class ReflectionUtils {
/**
* 獲取私有成員變量的值
* @param instance
* @param filedName
* @return
*/
public static Object getPrivateField(Object instance, String filedName) throws NoSuchFieldException, IllegalAccessException {
Field field = instance.getClass().getDeclaredField(filedName);
field.setAccessible(true);
return field.get(instance);
}
/**
* 設置私有成員的值
* @param instance
* @param fieldName
* @param value
* @throws NoSuchFieldException
* @throws IllegalAccessException
*/
public static void setPrivateField(Object instance, String fieldName, Object value) throws NoSuchFieldException, IllegalAccessException {
Field field = instance.getClass().getDeclaredField(fieldName);
field.setAccessible(true);
field.set(instance, value);
}
/**
* 訪問私有方法
* @param instance
* @param methodName
* @param classes
* @param objects
* @return
* @throws NoSuchMethodException
* @throws InvocationTargetException
* @throws IllegalAccessException
*/
public static Object invokePrivateMethod(Object instance, String methodName, Class[] classes, String objects) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
Method method = instance.getClass().getDeclaredMethod(methodName, classes);
method.setAccessible(true);
return method.invoke(instance, objects);
}
}
寫個簡單的單元測試如下:
/**
* @Author 落葉飛翔的蝸牛
* @Date 2018/3/10
* @Description
*/
@RunWith(SpringRunner.class)
public class ReflectionUtilsTest {
private String name;
private void setName(String name) {
this.name = name;
}
@Test
public void test() throws NoSuchFieldException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
ReflectionUtilsTest reflectionUtilsTest = new ReflectionUtilsTest();
//訪問私有屬性
System.out.println("name = " + ReflectionUtils.getPrivateField(reflectionUtilsTest, "name"));
//設置私有屬性
ReflectionUtils.setPrivateField(reflectionUtilsTest, "name", "張三");
System.out.println("name = " + ReflectionUtils.getPrivateField(reflectionUtilsTest, "name"));
//調用私有方法
ReflectionUtils.invokePrivateMethod(reflectionUtilsTest, "setName", new Class[]{String.class}, "李四");
System.out.println("name = " + ReflectionUtils.getPrivateField(reflectionUtilsTest, "name"));
}
}
輸出結果如下:
name = null
name = 張三
name = 李四