问题描述
我有一个像这样的接口,一些类实现了这个接口:
public interface MyInterface {}
public class Informations implements MyInterface {
@Command("version")
public void getVersion() {
System.out.println("1.0-SNAPSHOT");
}
}
public class Systems implements MyInterface {
@Command("os")
public void getOs() {
System.out.println("Linux OS");
}
}
我在这样的Map中收集了所有用@Command
注释的方法:
/* String is command */
private Map<String,Method> commandMaps = new ConcurrentHashMap<>();
现在,我要调用此方法:
Optional<String> optionalCommand = commandMaps.keySet().stream().filter(e -> e.equals(user_input_command)).findFirst();
if (optionalCommand.isPresent()) {
Method method = commandMaps.get(optionalCommand.get());
Class<?> declaringClass = method.getDeclaringClass();
System.out.println(">> " + method.getName());
System.out.println(">> " + declaringClass.getName());
method.invoke(declaringClass);
}
例如,用户输入os
命令和引用到Systems
类的declaringClass.getName(),但不能调用declaringClass。
因此,此代码导致IllegalArgumentException异常:
>> getOs
>> a.b.c.Systems
java.lang.IllegalArgumentException: object is not an instance of declaring class
如何解决此问题?
解决方法
通过反射调用方法时,需要将调用方法的对象作为第一个参数传递给Method#invoke。
// equivalent to s1.testParam("",obj)
testParamMethod.invoke(s1,"",obj);