反射獲取成員方法並使用
阿新 • • 發佈:2020-12-07
技術標籤:javase程式碼反射javac語言golangc++
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class demo {
public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
Class<?> c = Class.forName("javase.day22.demo01.Student");
Method[] methods = c.getDeclaredMethods();
//Method[] methods = c.getMethods();
for (Method method : methods) {
System.out.println( method);
}
System.out.println("----------");
Method m = c.getMethod("method1");
//獲取無參構造方法建立物件
Constructor<?> con = c.getConstructor();
Object obj = con.newInstance();
m.invoke(obj);
}
}