mardi 11 août 2020

Java reflection invoke on getDeclaringClass

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 ?





Aucun commentaire:

Enregistrer un commentaire