1. 程式人生 > 其它 >反射獲取成員方法並使用

反射獲取成員方法並使用

技術標籤: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); } }