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

xiaoxiao2021-02-28  58

问题:想调用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。

转载请注明原文地址: https://www.6miu.com/read-75949.html

最新回复(0)