獲取類執行時的屬性和方法
阿新 • • 發佈:2021-06-15
package cn.rushangw.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 aClass = Class.forName("cn.rushangw.reflection.User");
System.out.println(aClass.getName());//獲得包名+類名
System.out.println(aClass.getSimpleName());//獲得類名
//獲得類的屬性
Field[] fields = aClass.getFields();//只能找到public屬性
fields = aClass.getDeclaredFields();//可以找到全部的屬性
for (Field field : fields) {
System.out.println(field);
}
//獲得指定屬性的值
Field name = aClass.getDeclaredField("name");
System.out.println(name);
//獲得類的方法
Method[] methods = aClass.getMethods();//獲得本類及其父類的全部public方法
for (Method method : methods) {
System.out.println(method);
}
methods = aClass.getDeclaredMethods();//獲得本類的所有方法
for (Method method : methods) {
System.out.println(method);
}
//獲得指定的方法
Method getName = aClass.getMethod("getName", null);
Method setName = aClass.getMethod("setName", String.class);
System.out.println(getName);
System.out.println(setName);
//獲得指定的構造器
Constructor[] constructors = aClass.getConstructors();
for (Constructor constructor : constructors) {
System.out.println(constructor);
}
constructors = aClass.getDeclaredConstructors();
for (Constructor constructor : constructors) {
System.out.println(constructor);
}
//獲得指定的構造器
Constructor constructor = aClass.getConstructor(String.class, int.class, int.class);
System.out.println(constructor);
}
}