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);

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...