基本使用,就是这样。
具体使用,灵活多变,看自己怎么使用
//一般情况下,需要属性名,属性值
Field field = null; //属性名
String fieldName = null;//属性值
Class<?> aClass = XXX实体类.getClass();//实体类class
try {
field = aClass.getDeclaredField("字段名");
//打开私有访问
field.setAccessible(true);
//获取属性
String name = field.getName();
//获取属性值
String fieldName = (String) field.get(xxx实体类);
System.out.println(fieldName);
//给属性,设置值
field.set(xxx实体类,“想要设置的值”);
System.out.println(fieldName);
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
本文介绍了如何在Java中通过`get`和`set`方法操作实体类的私有字段,包括获取属性名、值,以及设置属性值,同时处理可能遇到的异常。适合理解类的内部访问和面向对象编程实践。
475

被折叠的 条评论
为什么被折叠?



