在做后台开发时实体的固定字段一般会抽取为一个父类,其他类继承该父类,例如主键字段,会放到一个父类中(IdEntity),其他类继承该类,但是我们在操作时操作的是子类,在通过子类获取父类属性是getDeclaredField和getField是不一样的,简单说
getDeclaredFiled 仅能获取类本身的属性成员(包括私有、共有、保护)
getField 仅能获取类(及其父类可以自己测试) public属性成员
因此在获取父类的私有属性时,要通过getSuperclass的之后再通过getDeclaredFiled获取。
父类,出去id作为父类字段
import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
import org.hibernate.annotations.GenericGenerator;
@MappedSuperclass
public abstract class IdEntity {
private String id;
@Id
@GeneratedValue(generator = "paymentableGenerator")
@GenericGenerator(name = "paymentableGenerator", strategy = "uuid")
@Column(name ="ID",nullable=false,length=32)
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
子类
public class Reflect extends IdEntity {
public String publicField;
private String privateField;
public Reflect(String publicField, String privateField) {
super();
this.publicField = publicField;
this.privateField = privateField;
}
public String getPrivateField() {
return privateField;
}
public void setPrivateField(String privateField) {
this.privateField = privateField;
}
}
测试类:
import java.lang.reflect.Field;
public class ReflectDemo {
/**
* @Description: TODO
* @param @param args
* @return void
* @throws SecurityException
* @throws NoSuchFieldException
* @throws IllegalAccessException
* @throws IllegalArgumentException
* @throws
* @author ydecai
* @date 2019-1-23
*/
public static void main(String[] args) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
Reflect re = new Reflect("zhangsan", "lisi");
re.setId("111");
//getDeclaredFiled获取本类属性
// Field publicField = re.getClass().getDeclaredField("publicField");
// System.out.println(publicField.get(re));
Field publicField = re.getClass().getField("publicField");
System.out.println(publicField.get(re));
//getField获取公有属性,包括父类的,下面语句报错
//Field privateField = re.getClass().getField("privateField");
Field privateField = re.getClass().getDeclaredField("privateField");
privateField.setAccessible(true);
System.out.println(privateField.get(re));
//获取父类私有属性并获取值
Field fileId = re.getClass().getSuperclass().getDeclaredField("id");
fileId.setAccessible(true);
System.out.println(fileId.get(re));
}
————————————————
版权声明:本文为CSDN博主「Apple_羊先森」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/caicaimaomao/article/details/86611897