package cn.usts.edu.getClassMethod05;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
/**
* @author :fly
* @description: 获取类的运行时结构(属性,方法,对象,构造器)
* 方法和构造器都有重载的存在,所以要给定参数类型,来定位到指定的构造器和方法
* @date :2021/10/28 14:26
*/
public class GetClassMethod {
public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, NoSuchMethodException {
Class<?> c1 = Class.forName("cn.usts.edu.getClassMethod05.User");
// 获取报名+类名
System.out.println(c1.getName());
// 获取类的名字
System.out.println(c1.getSimpleName());
// 获取类的属性:
Field[] fields = c1.getFields();// 只能获取到public修饰的属性
// 遍历
for (Field field : fields) {
System.out.println(field);
}
// 获取指定属性的值
Field name = c1.getDeclaredField("name");
System.out.println(name);
// 获得类的方法
System.out.println("=================");
Method[] methods = c1.getMethods();// 获取包括父类的所有方法
for (Method method : methods) {
System.out.println("包括父类的"+method);
}
Method[] declaredMethods = c1.getDeclaredMethods();// 获取当前类的方法
for (Method declaredMethod : declaredMethods) {
System.out.println("当前类的"+declaredMethod);
}
// 获取指定方法
System.out.println("============获取指定方法=========");
Method method03 = c1.getDeclaredMethod("method03", String.class);
System.out.println(method03);
Method method01_int = c1.getDeclaredMethod("method01", int.class);
System.out.println(method01_int);
// Method method01 = c1.getDeclaredMethod("method01", null); ide 推荐null不写
Method method01 = c1.getDeclaredMethod("method01");
System.out.println(method01);
// 获取构造器
System.out.println("============获取构造器=========");
Constructor<?>[] constructors = c1.getConstructors();
System.out.println("所有构造器");
for (Constructor<?> constructor : constructors) {
System.out.println(constructor);
}
// 获取指定构造器,因为方法和构造器都有重载的存在,所以要给定参数类型,来定位到指定的构造器和方法
Constructor<?> declaredConstructor = c1.getDeclaredConstructor(int.class, String.class);
System.out.println("指定构造器");
System.out.println(declaredConstructor);
}
}
// pojo 实体类
class User {
public int age;
public String name;
public User() {
}
public User(int age, String name) {
this.age = age;
this.name = name;
}
public void method01(){
System.out.println("method01");
}
public void method01(int age){
System.out.println("method02"+this.age+age);
}
private void method03(String name){
System.out.println(name+"method03"+this.name);
}
@Override
public String toString() {
return "User{" +
"age=" + age +
", name=" + name +
'}';
}
}