Java反射在getDeclaringClass上调用

问题描述

我有一个像这样的接口,一些类实现了这个接口:

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

在这样的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);