调用私有方法
public class PrivateMethod { private String sayHello(String name) { return "hello "+name; } }
测试
package com.java.test; import java.lang.reflect.Method; public class PrivateMethodTest { public static void main(String[] args)throws Exception { PrivateMethod p = new PrivateMethod(); Class<?> classType = p.getClass(); Method method = classType.getDeclaredMethod("sayHello", new Class[]{String.class}); method.setAccessible(true);//压制java的检查机制 String str = (String)method.invoke(p, new Object[]{"lzyer"}); System.out.println(str); } }
修改私有属性
public class PrivateField{ private String name="zhangsan"; public String getName() { return this.name; } }
测试
package com.java.test; import java.lang.reflect.Field; public class PrivateFieldTest { public static void main(String[] args)throws Exception { PrivateField p = new PrivateField(); Class<?> clazz = p.getClass(); Field field = clazz.getDeclaredField("name"); field.setAccessible(true);//压制java检查机制 field.set(p, "lisi"); System.out.println(p.getName()); } }
获取父类私有字段
@Test public void myTest() { CustomerApiInfoReqDtoNew t = new CustomerApiInfoReqDtoNew();//改成你要操作的子类 Class className = t.getClass(); Map<String, Object> param = new HashMap<>(); try{ for (; className != Object.class; className = className.getSuperclass()) {//获取本身和父级对象 Field[] fields = className.getDeclaredFields();//获取所有私有字段 for (Field field : fields) { field.setAccessible(true); param.put(field.getName(), field.get(t) == null ? "" : field.get(t)); } } System.out.print(JsonUtil.toJson(param));//打印子类和父类所有字段,注意:JsonUtil改成你自己的json解析工具 }catch (Exception e){ e.printStackTrace(); } }