afnan1992
afnan1992

Reputation: 57

No Such Method Exception thrown?

The problem I am facing is that when I try to pass an item with the value java.util.ArrayList,pass args[2] with value "add" and Method Parameter with the value Integer it throws a NoSuchMethodException? Any help in this regard is much appreciated. Stack Trace:

java.lang.NoSuchMethodException: java.util.ArrayList.add(java.lang.Integer)
at java.lang.Class.getDeclaredMethod(Unknown Source)
at com.acp.assignments.jcp.JCP.CallMethod(JCP.java:65)
at com.acp.assignments.jcp.JCP.InteractiveMode(JCP.java:129)
at com.acp.assignments.jcp.JCP.BatchOrInterActive(JCP.java:47)
at com.acp.assignments.jcp.Main.main(Main.java:29)

public void CallMethod(String[] args) throws Exception {
    HashMap<String, Object> temp=VariableslistHashMap;
    if(args[0].contains("call")) {
        for(Map.Entry<String, Object> item:temp.entrySet()) {
            for(Map.Entry<String, Object> MethodParameter:temp.entrySet()) {
                if(item.getKey().contains(args[1]) && MethodParameter.getKey().contains(args[3])) {
                    Method method=item.getValue().getClass().getDeclaredMethod(args[2],MethodParameter.getValue().getClass());
                    Object result=(Object) method.invoke(item.getClass(), MethodParameter.getValue());
                    System.out.println(result);
                }
            }
        }
    }
}

Upvotes: 0

Views: 1560

Answers (1)

Niels Bech Nielsen
Niels Bech Nielsen

Reputation: 4859

Try using Object as the key. Probably Integer is the type parameter, which is erased..

public static void main(String[] args) throws NoSuchMethodException, SecurityException {

    ArrayList<Integer> i = new ArrayList<>();
    i.getClass().getDeclaredMethod("add", new Class[] { Object.class } );  // Works
    i.getClass().getDeclaredMethod("add", new Class[] { Integer.class } ); // Fails
}

Upvotes: 1

Related Questions