获取类运行时类的完整结构
通过反射获取运行时类的完整结构
Field、Method、Constructor、Superclass、Interface、Annotation
- Field、Method、Constructor、Superclass、Interface、Annotation
- 实现的全部接口
- 所继承的父类
- 全部的构造器
- 全部的方法
- 全部的Field注解
- 。。。
/**
* @date 2021/11/30 19:21
*/
public class Test08 {
public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, NoSuchMethodException {
Class c1 = Class.forName("Study.User");
User user = new User();
c1 = user.getClass();
//获得类的名字
System.out.println(c1.getName()); //获得包名 + 类名
System.out.println(c1.getSimpleName()); //获得类名
System.out.println("====================================");
//获得类的属性
Field[] fields = c1.getFields();//只能找到Public属性
fields = c1.getDeclaredFields(); //找到全部的属性
for (Field field : fields){
System.out.println(field);
}
System.out.println("====================================");
//获得指定属性的值
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(); //获得本类的所有方法
System.out.println(declaredMethods);
System.out.println("====================================");
for (Method declaredMethod : declaredMethods){
System.out.println("declaredMethods:" + declaredMethod);
}
System.out.println("====================================");
//获得指定方法
//重载
Method getName = c1.getMethod("getName", null);
Method setName = c1.getMethod("setName", String.class);
System.out.println(getName);
System.out.println("====================================");
System.out.println(setName);
//获得构造器
System.out.println("====================================");
Constructor[] constructors = c1.getConstructors(); //获得本类的public方法
for (Constructor constructor : constructors){
System.out.println(constructor);
}
System.out.println("====================================");
constructors = c1.getDeclaredConstructors();//获得本类的全部方法
for (Constructor constructor : constructors){
System.out.println(constructor);
}
System.out.println("====================================");
//获得指定的构造器
Constructor declaredConstructor = c1.getDeclaredConstructor(String.class, int.class, int.class);
System.out.println("指定:" + declaredConstructor);
}
}