package hike.reflection;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
// 获得类的信息
public class Test07 {
public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, NoSuchMethodException {
Class c1 = Class.forName("hike.reflection.User");
// User user = new User();
// c1 = user.getClass();
// 获得类的名字
System.out.println(c1.getName()); // 获得 包 + 类名
System.out.println(c1.getSimpleName()); // 获得 类名
// 获得类的属性
Field[] fields = c1.getFields(); // 该方法只能获取 public修饰的属性
for (Field field : fields) {
System.out.println(field.toString());
}
fields = c1.getDeclaredFields(); // 该方法 能找到 所有的 属性
for (Field field : fields) {
System.out.println(field.toString());
}
System.out.println("=================================");
// 获得指定属性的值
// Field name = c1.getField("name"); // 报错 因为 name 是私有属性
Field name = c1.getDeclaredField("name");
System.out.println(name);
// 获得类的方法
System.out.println("========================================");
Method[] methods = c1.getMethods(); // 获得 本类 及 父类 的所有 public 方法
for (Method method : methods) {
System.out.println("正常的:" + method);
}
Method[] declaredMethods = c1.getDeclaredMethods(); // 获得本类的所有 方法 (包括私有的方法)
for (Method declaredMethod : declaredMethods) {
System.out.println("declaredMethod: " + declaredMethod);
}
// 获得 指定的方法
// 为什么需要 参数类型, 重载
Method getName = c1.getMethod("getName", null);
System.out.println(getName);
Method setName = c1.getMethod("setName", String.class);
System.out.println(setName);
System.out.println("=====================================");
// 获得指定的构造器
Constructor[] constructors = c1.getConstructors(); // 获得本类 的 public 方法
for (Constructor constructor : constructors) {
System.out.println(constructor);
}
constructors = c1.getDeclaredConstructors(); // 获得本类 的全部方法
for (Constructor constructor : constructors) {
System.out.println(constructor);
}
// 获得指定的构造器
Constructor declaredConstructor = c1.getDeclaredConstructor(String.class, int.class, int.class);
System.out.println("指定构造器:" + declaredConstructor);
}
}