使用反射访问方法

2022-01-27  本文已影响0人  鱿鱼炸酱面
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class InvokeMethod {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException, InstantiationException {
        Class<?> cls = Class.forName("java.lang.String");
        // 通过反射访问静态方法
        Method m = cls.getMethod("valueOf", char[].class);
        char[] chars = {'l', 'o', 'v', 'e'};
        Object res = m.invoke(null, chars);
        System.out.println(res);

        // 通过反射访问实例方法
        Method m2 = cls.getMethod("startsWith", String.class);
        // 通过反射访问构造方法
        Object obj = cls.getConstructor(char[].class).newInstance(chars);
        boolean res2 = (boolean) m2.invoke(obj, "l");
        System.out.println(res2);
    }
}
上一篇 下一篇

猜你喜欢

热点阅读