1, Class object to get the member variables:
Common method of class Class:
Creating the Person class:
package pers.reflect.person; public class Person { private String name; private int age; public String hobby; public String height; protected String sex; String address; public Person(){ } public Person(String name,int age){ this.name=name; this.age=age; } @Override public String toString() { return "Person [name=" + name + ", age=" + age + ", hobby=" + hobby + ", height=" + height + ", sex=" + sex + ", address=" + address + "]"; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
import java.lang.reflect.Field; import pers.reflect.person.Person; public class ReflectDemo { public static void main(String[] args) throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException { Class c = Person.class; System.out.println("getFields(),获取公共的成员变量:"); Field[] fields = c.getFields(); for (Field field : fields) { System.out.println(field); } . The System OUT .println ( " getField (), acquired specified common member variables: " ); Field, hobbyField = c.getField ( " Hobby " ); the System. OUT .println (hobbyField); the System. OUT .println ( " getDeclaredFields (), get all of the member variables, regardless of the modifier. " ); Field, [] fields1 = c.getDeclaredFields (); for (Field, Field: fields1) { . the System OUT .println (Field); } the System. OUT .println (" Get the specified private member variables " ); Field, the nameField = c.getDeclaredField ( " Age " ); the System. OUT .println (the nameField); } }
2, the Field class common method:
(1) the type of the return variable:
(2) Returns the name of the property: