checkMethod.invoke(userService, new Object[]{user});按顺序写到Object数组中就可以了
Class clazz =Class.forName("com.test.Service"); Object o =clazz.newInstance(); User user =new User(); user.setUsername("zhangsan"); Method method =clazz.getMethod("f",null); method.invoke(o,new Object[]{user}); 报错: java.lang.NoSuchMethodException: com.test.Service.f() at java.lang.Class.getMethod(Class.java:978) at com.test.Test.main(Test.java:10)
Object o =clazz.newInstance();
User user =new User();
user.setUsername("zhangsan");
Method method =clazz.getMethod("f",null);
method.invoke(o,new Object[]{user});
报错:
java.lang.NoSuchMethodException: com.test.Service.f()
at java.lang.Class.getMethod(Class.java:978)
at com.test.Test.main(Test.java:10)
Method method =clazz.getMethod("f",new Class[]{User.class});
其实我不知道为什么你非要用reflect,一般来说你可以定义一个Interface,将需要的方法写在里面。然后你的实现类实现这个接口就行了,这样代码又简洁