简体   繁体   中英

Argument type mismatch when attempting to invoke method

Say I have a parameters array:

Object[] parameters;

I also have a types list, that stores parameter types of a method.

List<Class<?>> types = Arrays.asList(Taxi.class, Bus.class);

Next instantiating the array:

parameters = new Object[types.size()];

Now, I fill the parameters array, with the given types in the types list:

int index = 0;
for (Class<?> type : types) {
    if (Taxi.class.isAssignableFrom(type)) {
        parameters[index] = new Taxi();
    } else if (Bus.class.isAssignableFrom(type)) {
        parameters[index] = new Bus();
    } 
    index ++;
}

Now I try to invoke the method that has the exactly same parameters as the types list:

someMethod.invoke(someObject, parameters);

The someMethod has the following signature:

public void someMethod(Taxi taxi, Bus bus);

And Java gives me an IllegalArgumentException: argument type mismatch . I understand why would this happen, as parameters is an Object array; are there any workarounds, though? Maybe like casting? But how?

Note that the 1) The objects in types list may NOT have a common superclass. 2) I know it's strange to not directly call the method but used the reflections to do so; this is because I am trying to implement an Event-like system, which requires "filling in" method parameters dynamically. 3) Parameter types (the types list) are already determined before the compilation.

The way of obtaining methods:

// Collect methods
Set<Method> methods;
Method[] publicMethods = someClass.getClass().getMethods();
methods = new HashSet<>(publicMethods.length, Float.MAX_VALUE);
Collections.addAll(methods, publicMethods);
Collections.addAll(methods, listener.getClass().getDeclaredMethods());
// Find annotated methods
for (final Method method : methods) {
    method.setAccessible(true);
    // Code from above
}

Make an common super class like vehicle and derive bus and taxi from that class.

Then you just have to make List<Vehicle> types = Arrays.asList(Taxi.class, Bus.class);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM