public class Main {
public static void main(String[] args) throws Exception {
Class person = Class.forName("test.Person");
Class person1 = Person.class;
Person p = new Person();
Class person2 = p.getClass();
System.out.println(person);
System.out.println(person1);
System.out.println(person2);
}
}
public class Person {
public String name;
private int age;
public String sex;
}
Main类
public class Main {
public static void main(String[] args) throws Exception {
Class person = Class.forName("test.Person");
Field[] fields = person.getFields();
System.out.println("getFields():只能获得公有的属性");
for(int i = 0;i<fields.length;i++){
System.out.println(fields[i]);
}
System.out.println("-----------------------------");
Field[] fields1 = person.getDeclaredFields();
System.out.println("getDeclaredFields():能获得所有的属性");
for(int i = 0;i<fields1.length;i++){
System.out.println(fields1[i]);
}
System.out.println("-----------------------------");
Field field = person.getField("name");
System.out.println("getField():获得单个公有属性");
System.out.println(field);
}
}
程序运行结果
getFields():只能获得公有的属性
public java.lang.String test.Person.name
public java.lang.String test.Person.sex
-----------------------------
getDeclaredFields():能获得所有的属性
public java.lang.String test.Person.name
private int test.Person.age
public java.lang.String test.Person.sex
-----------------------------
getField():获得单个公有属性
public java.lang.String test.Person.name