目录
1. getField(StringfieldName)【public】
!!public方法可以获取,但是protected,private不可以获取哦~
3. getDeclaredField(String name)方法【public/protected/private】
!!public/protected/private/final/native都可获取哦!耶!
4.getDeclaredFields()【public/protected/private】
四、 Field获取
Person类:
package people.constructor;
import java.util.Date;
/**
* @author: y9
* @Date: 2021/09/26
*/
public class Person {
public String name;
protected boolean sex;
private int age;
}
1. getField(StringfieldName)【public】
代码:
package people.constructor;
import java.lang.reflect.Field;
/**
* @author: y9
* @Date: 2021/09/26
*/
public class Bootstrap2 {
public static void main(String[] args) throws NoSuchFieldException{
Class clazz = Person.class;
Field field = clazz.getField("name");
System.out.println(field.toString());
//field = clazz.getField("sex"); //测试protected权限
field = clazz.getField("age"); //测试private权限
}
}
public java.lang.String people.constructor.Person.name
Exception in thread "main" java.lang.NoSuchFieldException: age
at java.base/java.lang.Class.getField(Class.java:2092)
at studentsa/people.constructor.Bootstrap2.main(Bootstrap2.java:20)
!!protected、private不可以获取哦~
2. getFields()方法【public】
代码:
package people.constructor;
import java.lang.reflect.Field;
/**
* @author: y9
* @Date: 2021/09/26
*/
public class Bootstrap2 {
public static void main(String[] args) throws NoSuchFieldException{
Class clazz = Person.class;
Field[] fields = clazz.getFields();
for(Field field: fields) {
System.out.println(field.toString());
}
}
}
public java.lang.String people.constructor.Person.name
!!public方法可以获取,但是protected,private不可以获取哦~
3. getDeclaredField(String name)方法【public/protected/private】
代码:
package people.constructor;
import java.lang.reflect.Field;
/**
* @author: y9
* @Date: 2021/09/26
*/
public class Bootstrap2 {
public static void main(String[] args) throws NoSuchFieldException{
Class clazz = Person.class;
Field field = clazz.getDeclaredField("name");
System.out.println(field.toString());
field = clazz.getDeclaredField("sex"); //测试protected权限
System.out.println(field.toString());
field = clazz.getDeclaredField("age"); //测试private权限
System.out.println(field.toString());
}
}
public java.lang.String people.constructor.Person.name
protected boolean people.constructor.Person.sex
private int people.constructor.Person.age
!!public/protected/private/final/native都可获取哦!耶!
4.getDeclaredFields()【public/protected/private】
代码:
package people.constructor;
import java.lang.reflect.Field;
/**
* @author: y9
* @Date: 2021/09/26
*/
public class Bootstrap2 {
public static void main(String[] args) throws NoSuchFieldException{
Class clazz = Person.class;
Field[] fields = clazz.getDeclaredFields();
for(Field field: fields) {
System.out.println(field.toString());
}
}
}
public java.lang.String people.constructor.Person.name
protected boolean people.constructor.Person.sex
private int people.constructor.Person.age