问题描述
public interface MyInterface {}
public class @R_276_4045@ions 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");
}
}
/* 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);