集册 Java实例教程 使用反射按名称调用方法

使用反射按名称调用方法

欢马劈雪     最近更新时间:2020-01-02 10:19:05

446
使用反射按名称调用方法
/* 
 来自 
*n o w    j a v a  . c o m*/

import java.lang.reflect.InvocationTargetException;

import java.lang.reflect.Method;


class AnotherClass {

    private void m() {

    }

}


public class MethodTroubleAgain {

    public static void main(String... args) {

        AnotherClass ac = new AnotherClass();

        try {

            Class<?> c = ac.getClass();// 来 自 nowjava.com - 时代Java

            Method m = c.getDeclaredMethod("m");

            //        m.setAccessible(true);      // solution

            Object o = m.invoke(ac); // IllegalAccessException


            // production code should handle these exceptions more gracefully

        } catch (NoSuchMethodException x) {

            x.printStackTrace();

        } catch (InvocationTargetException x) {

            x.printStackTrace();

        } catch (IllegalAccessException x) {

            x.printStackTrace();

        }

    }

}


展开阅读全文