广州飞狐科技有限公司官网
技术文章
2020-12-27 17:35:10

JAVA:反射中getMethod与getDeclaredMethod区别

分享到:
反射
对于任何一个类,都能知道这个类所有的属性和方法;对于任何一个对象,都能够调用它的任意方法和属性;这种动态获取信息以及动态调用对象方法的功能称为Java语言的反射机制
getMethod()返回某个类的所有公用(public)方法包括其继承类的公用方法,当然也包括它所实现接口的方法
getDeclaredMethod()对象表示的类或接口声明的所有方法,包括公共、保护、默认(包)访问和私有方法,但不包括继承的方法。当然也包括它所实现接口的方法

public class Robot {
    private String name;
    public void sayHi(String hi){
        System.out.println(hi+ " "+name);
    }
    private String throwHello(String tag){
        return "hello"+ tag;
    }
}


示例:

public class ReflectSample {
    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException,
        InstantiationException, NoSuchMethodException, InvocationTargetException, NoSuchFieldException {

        Class rc = Class.forName("com.example.reflect.Robot");
        Robot r = (Robot) rc.newInstance();
        //基础
        Method getHello = rc.getDeclaredMethod("throwHello",String.class);
        getHello.setAccessible(true);
        Object str = getHello.invoke(r,"Bob");
        System.out.println("getHello result is " + str);

        //公共
        Method sayHi = rc.getMethod("sayHi", String.class);
        sayHi.invoke(r,"welcome");

        Field name = rc.getDeclaredField("name");
        name.setAccessible(true);
        name.set(r,"Alice");
        sayHi.invoke(r,"welcome");
    }
}
————————————————
版权声明:本文为CSDN博主「loulanyue_」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/loulanyue_/article/details/103568496
上一篇:学 Python 都用来干嘛的
下一篇:JVM 里 new 对象时,堆会发生什么吗?怎么去设计JVM的堆的线程安全