如何解决Java反射在getDeclaringClass上调用
我有一个像这样的接口,一些类实现了这个接口:
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);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。