运用反射时报错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

posted @ 2017-08-23 09:38  疯子110  阅读(8998)  评论(0编辑  收藏  举报