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类的实例
Class<?> c1 = Class.forName("注解和反射.reflection.User");
//获取类的名字
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);
}
//获取指定属性的值
Field name = c1.getDeclaredField("age");
System.out.println(name);
//获得类的方法
System.out.println("===获得类的方法===");
Method[] methods = c1.getMethods();//获取本类及其父类的全部public方法
for (Method method : methods) {
System.out.println("正常的:"+method);
}
methods = c1.getDeclaredMethods();//获得本类的所有的方法
for (Method method : methods) {
System.out.println("getDeclaredMethods:"+method);
}
//获得指定的方法
Method getName = c1.getMethod("getAge",null);
Method setName = c1.getMethod("setAge", int.class);
System.out.println(getName);
System.out.println(setName);
//获得指定的构造器
System.out.println("===获得指定的构造器===");
Constructor[] constructors = c1.getConstructors();
for (Constructor constructor : constructors) {
System.out.println(constructor);
}
constructors = c1.getDeclaredConstructors();
for (Constructor constructor : constructors) {
System.out.println("getDeclaredConstructors"+constructor);
}
//获得指定的构造器
Constructor<?> constructor = c1.getConstructor(String.class, int.class, int.class);
System.out.println("指定构造器:"+constructor);
}
}
//实体类:pojo entity
class User{
private String name;
private int id;
private int age;
public User() {
}
public User(String name, int id, int age) {
this.name = name;
this.id = id;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
java通过反射获取类的信息(类的名字,属性,方法,构造方法)
最新推荐文章于 2024-05-27 20:55:58 发布