使用反射获取泛型对象的方法、属性、注解。
本文使用以下实体进行测试:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| public class AaDTO { @NotNull private Integer aaInteger; public String aaString;
private Integer getAaInteger() { return aaInteger; }
public void setAaInteger(Integer aaInteger) { this.aaInteger = aaInteger; }
public String getAaString() { return aaString; }
public void setAaString(String aaString) { this.aaString = aaString; }
public AaDTO(Integer aaInteger, String aaString) { this.aaInteger = aaInteger; this.aaString = aaString; }
public AaDTO() { } }
|
获取字段值
使用getFields()
获取所有public
字段,但无法获取到private
字段;
使用getDeclaredField(String name)
获取指定public
字段;
对field
设置field.setAccessible(true)
可获取到private
字段;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| public static <T> void getFields(T t) { Class<?> tClass = t.getClass(); Field[] fields = tClass.getFields(); for (Field field : fields) { System.out.println("field name:" + field.getName()); try { System.out.println("field value:" + field.get(t)); } catch (IllegalAccessException e) { e.printStackTrace(); } } try { Field auditResult = tClass.getDeclaredField("aaString"); auditResult.setAccessible(true); System.out.println("aaString value:" + auditResult.get(t)); } catch (NoSuchFieldException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } }
|
获取方法并调用
使用getDeclaredMethods()
获取所有方法,包括private
方法,但是在调用private
方法时会抛出IllegalAccessException
;
使用getDeclaredMethod(String name, Class<?>... parameterTypes)
获取指定public
方法。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| public static <T> void getMethods(T t) { Class<?> tClass = t.getClass(); Method[] methods = tClass.getDeclaredMethods(); Arrays.stream(methods) .filter(method->method.getName().contains("get")) .forEach(method->{ try { System.out.println("调用了方法:" + method.getName() + " 值为:" + method.invoke(t)); } catch (IllegalAccessException e) { System.out.println("非法调用了方法:" + method.getName()); method.setAccessible(true); try { System.out.println("修改为可访问后,方法:" + method.getName() + " 值为:" + method.invoke(t)); } catch (IllegalAccessException | InvocationTargetException illegalAccessException) { illegalAccessException.printStackTrace(); } } catch (InvocationTargetException e) { e.printStackTrace(); } });
}
|