运用反射时报错java.lang.NoSuchMethodException,以解决,记录一下


问题:想调用service类中的私有方法时, Method target=clz.getMethod("say", String.class);用Class的getMethod报错Java.lang.NoSuchMethodException。

 

解决方案:查了下Class的文档,该类下原来有两个方法:getMethod,getDeclaredMethod。看了下说明大概的意思就是getMethod只能调用public声明的方法,而getDeclaredMethod基本可以调用任何类型声明的方法

 

调用详细代码:

public class Client5 {
    @SuppressWarnings("unused")
    private String say(String content){
        return "hi,"+content;
    }
    
    public String show(String content){
        return "hi,"+content;
    }
}

public class Client4 {
    public static void main(String args[]) throws Exception{
        Class<Client5> clz=Client5.class;
        Client5 obj=(Client5)clz.newInstance();
        Method target=clz.getDeclaredMethod("say", String.class);
        target.setAccessible(true);
        System.out.println(target.invoke(obj, "I am Caomr"));
    }
}

 

笔记:以后用放射多用getDeclaredMethod,尽量少用getMethod


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM