qq_31960469
qq_31960469
采纳率100%
2019-05-20 23:42

Class.getmethod如何获取到参数带有class<?>的方法?

5
已采纳

相关代码:
public class ReflectDemo {
private void t00(Class<?> unknown,String str)
{
System.out.println("t0");
}
}
public void test01()
{
Class<?> unknown= null;
try {
Method method= ReflectDemo.class.getDeclaredMethod("t00",unknown,String.class);
method.setAccessible(true);
method.invoke(new ReflectDemo(),"a","b");
} catch (Exception e) {
e.printStackTrace();
}
}
报错信息:java.lang.NoSuchMethodException: Demo.ReflectDemo.t00(null, java.lang.String)

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

2条回答

  • m0_37132783 syd_no1 2年前

    public class ReflectDemo {
    private void t00(Class<?> unknown,String str)
    {
    System.out.println("t0");
    }
    }
    class Test{

    public static void main(String[] args) {
        test01();
        test01();
    }
    
    public static void test01() {
        try {
            Class<?> unknown = String.class;
            Class <ReflectDemo> demoClass = ReflectDemo.class;
            Method method= demoClass.getDeclaredMethod("t00", unknown.getClass(), String.class);
            method.setAccessible(true);
            method.invoke(new ReflectDemo(),String.class, "b");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    public static void test02() {
        try {
            Class<?> unknown = Object.class;
            Class <ReflectDemo> demoClass = ReflectDemo.class;
            Method method= demoClass.getDeclaredMethod("t00", unknown.getClass(), String.class);
            method.setAccessible(true);
            method.invoke(new ReflectDemo(),Object.class, "b");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    

    }

    Method method= demoClass.getDeclaredMethod("t00", unknown.getClass(), String.class);

    可以的话自己debug一下吧

    点赞 评论 复制链接分享
  • caozhy 回答这么多问题就耍赖把我的积分一笔勾销了 2年前