反射_5.方法的反射调用

/**
 * 成员方法和静态方法的反射案例
 * 
 * @author linguoren
 *
 */
public class T1_InvokeMethod {
    public static void main(String[] args) {
        /**
         * 调用
         */
        String str = new String("123");
        try {
            // 1.使用Class中的getMethod方法获取该方法对象
            Method method = String.class.getMethod("charAt", int.class);
            // 2.method调用invoke方法传入要调用的对象(如果是静态方法则传入null),和所需参数(支持可变参)
            char res = (char) method.invoke(str, 1);
            System.out.println(res);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

 

posted @ 2018-01-22 11:16  Dylan丶Djm  阅读(129)  评论(0编辑  收藏  举报