英文:
Java reflection invoke on 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");
}
}
我正在收集所有带有@Command
注解的方法,存储在一个Map中,就像这样:
/* 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
命令,declaringClass.getName()
引用了Systems
类,但不能调用declaringClass
。因此,这段代码会抛出IllegalArgumentException
异常:
>> getOs
>> a.b.c.Systems
java.lang.IllegalArgumentException: object is not an instance of declaring class
如何修复这个问题?
英文:
I have a interface like this and some classes implemented this interface:
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");
}
}
I collecting all methods annotated @Command
in a Map like this :
/* String is command */
private Map<String, Method> commandMaps = new ConcurrentHashMap<>();
Now , I want invoke this methods :
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);
}
for example user enter os
command and declaringClass.getName() referenced to Systems
class but can not invoking declaringClass .
so , this code result IllegalArgumentException exception :
>> getOs
>> a.b.c.Systems
java.lang.IllegalArgumentException: object is not an instance of declaring class
How can fix this problem ?
答案1
得分: 1
When you invoke a method via reflection, you need to pass the object you are calling the method on as the first parameter to Method#invoke.
// equivalent to s1.testParam("", obj)
testParamMethod.invoke(s1, "", obj);
英文:
When you invoke a method via reflection, you need to pass the object you are calling the method on as the first parameter to Method#invoke.
// equivalent to s1.testParam("", obj)
testParamMethod.invoke(s1, "", obj);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论