利用反射获取类的运行时结构(属性,方法,对象,构造器)
package cn.usts.edu.getClassMethod05;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
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();
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");
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);
}
}
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 +
'}';
}
}