获取运行时类的完整结构
通过反射获取运行时类的完整结构
Field Method Constructor Superclass Interface Annotation
- 实现的全部接口
- 所继承的父类
- 全部的构造器
- 全部的方法
- 全部的Field
- 注解
- …
案例
package 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("Reflection.User");
//获得类的名字
//获得包名+类名
System.out.println(c1.getName());
//获得类名
System.out.println(c1.getSimpleName());
//获得类的属性
System.out.println("===============================");
Field[] fields = c1.getFields(); //只能找到public属性
Field[] fields1 =c1.getDeclaredFields(); //找到全部的属性
for (Field field : fields1) {
System.out.println(field);
}
//获取指定属性的值
Field name = c1.getDeclaredField("name");
System.out.println(name);
//获得类的方法
System.out.println("===========================");
Method[] method = c1.getMethods(); //获取本类及其父类的全部public方法
for (Method method1 : method) {
System.out.println("正常的:"+method1);
}
Method[] method1= c1.getDeclaredMethods(); //获取本类的所有方法
for (Method method2 : method1) {
System.out.println(method2);
}
//获得指定方法
//重载
System.out.println("============获取指定方法==============");
Method getName = c1.getMethod("getName", null);
Method setName = c1.getMethod("setName", String.class);
System.out.println(getName);
System.out.println(setName);
//获得公共的构造器 public
System.out.println("=================================");
Constructor[] cts1 = c1.getConstructors();
for (Constructor constructor : cts1) {
System.out.println(constructor);
}
//获取全部的构造器
Constructor[] dctts = c1.getDeclaredConstructors();
for (Constructor dctt : dctts) {
System.out.println(dctt);
}
//获取指定的构造器
Constructor constructor111 = c1.getDeclaredConstructor(int.class,String.class,int.class);
System.out.println("指定:"+constructor111);
}
}