A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 杨庆雷 中级黑马   /  2014-8-8 02:10  /  1563 人查看  /  4 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

  1. public class Test {
  2.        
  3.         public static void main(String[] args) {
  4.                 try {
  5.                         Object obj = ReflectPiont.class.newInstance();
  6.                         Method method = obj.getClass().getMethod("printStr",String.class);
  7.                         String str = "aaa";
  8.                         method.invoke(null,str);
  9.                        
  10.                         System.out.println("aaa");
  11.                 } catch (Exception e) {
  12.                         e.printStackTrace();
  13.                 }
  14.                
  15.         }

  16. }

  17. class ReflectPiont{
  18.        
  19.         private static void printStr(String str) {
  20.                 // TODO Auto-generated method stub
  21.                 System.out.println(str);
  22.         }
  23. }
复制代码
java.lang.NoSuchMethodException: com.itheima.ReflectPiont.printStr(java.lang.String)
        at java.lang.Class.getMethod(Unknown Source)
        at com.itheima.Test7.main(Test7.java:14)


这是怎么出错的

4 个回复

倒序浏览
本帖最后由 杨庆雷 于 2014-8-8 02:35 编辑
  1. public class Test {
  2.        
  3.         public static void main(String[] args) {
  4.                 try {
  5.                         Test test = Test.class.newInstance();
  6.                         Method method = test.getClass().getMethod("printStr");
  7.                         method.invoke(test);
  8.                 } catch (Exception e) {
  9.                         e.printStackTrace();
  10.                 }
  11.         }
  12.         private void printStr() {
  13.                 // TODO Auto-generated method stub
  14.                 System.out.println("aaa");
  15.         }
  16. }
复制代码
原因找到了  把private void printStr()改为public void printStr()
回复 使用道具 举报
呵呵  测试题吧
回复 使用道具 举报
getMethod是获取公共成员,你用getDeclaredMethod可以获取在这个类你面定义的所有方法。
回复 使用道具 举报
getDeclaredMethod获取声明你的方法:也就是能够获取一个类中的所有方法
getMethod只能获取一个类中的公共方法
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马