java反射中,获取字段属性有两种方法,getDeclaredFields和getFields。
下面通过例子展示不同之处:
Person类:
package cn.wzy.FieldAndMethod;
/**
* @author wzy 不短不长八字刚好.
* @since 2018/9/14 9:39
*/
public class Person {
private String name;
private String age;
protected String sex;
protected String add;
public String sch;
public String city;
public String getName() {
return name;
}
public String getAge() {
return age;
}
public String getSex() {
return sex;
}
public String getAdd() {
return add;
}
public String getSch() {
return sch;
}
public String getCity() {
return city;
}
}
测试类:
package cn.wzy.FieldAndMethod;
import java.lang.reflect.Field;
import java.sql.SQLOutput;
/**
* @author wzy 不短不长八字刚好.
* @since 2018/9/14 9:38
*/
public class Main {
public static void main(String[] args) {
Class<Person> clazz = Person.class;
Field[] fields = clazz.getFields();
for (Field field: fields) {
System.out.println(field.getName());
}
System.out.println("========*****========");
Field[] declaredFields = clazz.getDeclaredFields();
for (Field field: declaredFields) {
System.out.println(field.getName());
}
}
}
结果:
sch
city
========*****========
name
age
sex
add
sch
city
表明getFields只会获取公有字段,getDeclaredFields会获取所有的申明过的字段。
验证getDeclaredFields是否只会获取所有申明字段:
package cn.wzy.FieldAndMethod;
/**
* @author wzy 不短不长八字刚好.
* @since 2018/9/14 9:43
*/
public class User extends Person {
}
测试:
package cn.wzy.FieldAndMethod;
import java.lang.reflect.Field;
/**
* @author wzy 不短不长八字刚好.
* @since 2018/9/14 9:38
*/
public class Main {
public static void main(String[] args) {
Class<User> clazz = User.class;
Field[] fields = clazz.getFields();
for (Field field : fields) {
System.out.println(field.getName());
}
System.out.println("========*****========");
Field[] declaredFields = clazz.getDeclaredFields();
for (Field field : declaredFields) {
System.out.println(field.getName());
}
}
}
输出:
sch
city
========*****========
结果表明getField返回公有字段,不管是继承还是自己申明的,而getDeclaredFields只能是自己申明的字段;
如果说要获取自己父类的私有字段并修改值,比如说User类想修改自己继承来的name属性:
package cn.wzy.FieldAndMethod;
import java.lang.reflect.Field;
/**
* @author wzy 不短不长八字刚好.
* @since 2018/9/14 10:09
*/
public class GetSuperField {
public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
Class<User> clazz = User.class;
User user = new User();
Field field = clazz.getSuperclass().getDeclaredField("name");
field.setAccessible(true);
field.set(user, "wzy");
System.out.println(user.getName());
}
}