What is Field
Field is a class located under the java.lang.reflect package. In Java reflection, the Field class describes the attribute information of the class, and its functions include:
- Get the type of the member variable of the current object
- reset member variable
Field common methods
getType(): 获取属性声明时类型对象(返回class对象)
getGenericType() : 返回属性声的Type类型
getName() : 获取属性声明时名字
getAnnotations() : 获得这个属性上所有的注释
getModifiers() : 获取属性的修饰
isEnumConstant() : 判断这个属性是否是枚举类
isSynthetic() : 判断这个属性是否是 复合类
get(Object obj) : 取得obj对象这个Field上的值
set(Object obj, Object value) : 向obj对象的这个Field设置新值value
Field gets the attribute name and attribute value of the entity class
- Get the entity class and return an array. The data of the array is the field in the entity class
- Add setAccessible() because the field is modified with private
- Output attribute names and attribute values
EntityUserVO
/**
* @Author charles.yao
* @Description
* @Date 2022/12/26 22:45
*/
public class UserVO {
private String name;
private String lastName;
private Integer age;
public UserVO(String name, String lastName, Integer age) {
this.name = name;
this.lastName = lastName;
this.age = age;
}
public UserVO() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
test class
/**
* @Author charles.yao
* @Description
* @Date 2022/12/26 22:46
*/
public class Test {
public static void main(String[] args) {
UserVO userVO =new UserVO();
userVO.setAge(11);
userVO.setLastName("老张");
userVO.setName("小名");
//获取useroVo所有字段
Field[] fields = userVO.getClass().getDeclaredFields();
try {
for (Field field : fields) {
field.setAccessible(true);
System.out.println("字段名称"+field.getName()+"=字段值"+field.get(userVO));
}
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
operation result
字段名称name====字段值小名
字段名称lastName====字段值老张
字段名称age====字段值11