package classloaderdemo4;
import java.lang.reflect.Field;
public class FieldDemo2 {
public static void main(String[] args) throws Exception {
// method1();
// method2();
// method3();
// method4();
}
private static void method4() throws ClassNotFoundException, NoSuchFieldException {
// 获取对应的Class对象
Class<?> aClass = Class.forName("classloaderdemo4.Student");
// 获取单个成员变量对象(只有公共)
Field field = aClass.getField("name");
System.out.println(field);
}
private static void method3() throws ClassNotFoundException, NoSuchFieldException {
// 获取对应的Class对象
Class<?> aClass = Class.forName("classloaderdemo4.Student");
// 获取单个成员变量对象(私有和公共都可以)
Field declaredField = aClass.getDeclaredField("money");
System.out.println(declaredField);
}
private static void method2() throws ClassNotFoundException {
// 获取对应的Class对象
Class<?> aClass = Class.forName("classloaderdemo4.Student");
// 获取所有非私有的成员变量对象
// 返回一个集合
Field[] fields = aClass.getFields();
for (Field field : fields) {
System.out.println(field);
}
}
private static void method1() throws ClassNotFoundException {
// 获取对应的Class对象
Class<?> aClass = Class.forName("classloaderdemo4.Student");
// 获取所有的成员变量对象(私有和公共)
// 返回一个集合
Field[] declaredFields = aClass.getDeclaredFields();
for (Field declaredField : declaredFields) {
System.out.println(declaredField);
}
}
}
package classloaderdemo4;
public class Student {
public String name;
public int age;
public String gender;
private int money = 300;
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
", gender='" + gender + '\'' +
", money=" + money +
'}';
}
}