获取运行时类的完整结构
![image]()
package com.guo.reflection;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
//获得类的信息
public class Test08 {
public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, NoSuchMethodException {
Class c1 = Class.forName("com.guo.reflection.User");
//获得类的名字
//包名+类名
System.out.println(c1.getName()); //com.guo.reflection.User
//类名
System.out.println(c1.getSimpleName()); //User
//获得类的属性
System.out.println("=============================");
Field[] fields = c1.getFields(); //只能找到public属性
for (Field field : fields) {
System.out.println(field);
}
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(); //获得本类及其父类的全部方法
for (Method method : methods) {
System.out.println("正常的"+method);
}
System.out.println("=======================");
methods = c1.getDeclaredMethods(); //获得本类的全部方法
for (Method method : methods) {
System.out.println("本类的"+method);
}
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();
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);
}
}