java反射 获取类结构
package AnnotationTest.AnnotationTest01;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class Test03 {
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException, NoSuchFieldException {
//获得类
// Class c1 = Class.forName("AnnotationTest.AnnotationTest01.User");
User user= new User();
Class c1 = user.getClass();
//获得类的名字
System.out.println("-----获得类的名字-----");
System.out.println(c1.getName());//类名+包名
System.out.println(c1.getSimpleName());//类名
//获得类的属性
System.out.println("-----获得类的属性-----");
System.out.println("-----getFields-----");
Field[] fields = c1.getFields();//只获取public属性
for (Field field : fields) {
System.out.println(field);
}
System.out.println("-----getDeclaredFields-----");
fields = c1.getDeclaredFields();//获取所有属性
for (Field field : fields) {
System.out.println(field);
}
System.out.println("-----getDeclaredFields-----");
Field field = c1.getDeclaredField("name");//获取指定属性
System.out.println(field);
//获得类的方法
System.out.println("-----获得类的方法-----");
System.out.println("-----getMethods-----");
Method[] methods = c1.getMethods();//获取本类和父类所有public方法
for (Method method : methods) {
System.out.println(method);
}
System.out.println("-----getDeclaredMethods-----");
methods = c1.getDeclaredMethods();//获取本类的所有方法
for (Method method : methods) {
System.out.println(method);
}
System.out.println("-----getMethod(无参数)-----");
Method method = c1.getMethod("getName",null);//获取指定方法(无参数)
System.out.println(method);
System.out.println("-----getMethod(带参数)-----");
method = c1.getMethod("setName",String.class);//获取指定方法(带参数),因为有重载
System.out.println(method);
//获得构造器
System.out.println("-----获得构造器-----");
System.out.println("-----getConstructors-----");
Constructor[] constructors = c1.getConstructors();//获得public的构造器
for (Constructor constructor : constructors) {
System.out.println(constructor);
}
System.out.println("-----getDeclaredConstructors-----");
constructors = c1.getDeclaredConstructors();//获得所有构造器
for (Constructor constructor : constructors) {
System.out.println(constructor);
}
System.out.println("-----getConstructor-----");
Constructor constructor = c1.getConstructor(String.class,int.class);//获得指定构造器
System.out.println(constructor);
}
}
package AnnotationTest.AnnotationTest01;
public class User {
private String name;
private int age;
public User() {
}
public User(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}