I would like to avoid the if else, in java this:
for (Class clazz : method.getParameterTypes()) {
if (SomeClass.class.isAssignableFrom(clazz)) {
arguments[i] = onearg;
} else if (SomeOtherClass.class.isAssignableFrom(clazz)) {
arguments[i] = someotherarg;
}
}
can anyone suggest how to do this? thanks
You could store the classes and their arguments in a
Map<Class<?>, Object>and iterate the map, this would replace the if-else construct by an iteration loop with one if-statement.For instance like this:
The concrete implementation depends on your classes. If the classes in your map have no relationship between each other (e.g. superclass, subclass, interface, etc.) then you can apply the code directly. Otherwise, as bestsss has pointed ought you should stick to super class/interface iteration in order to preserve the class hierarchy.
Further your could investigate into Java Annotations, though I am not 100% sure how to apply them in your case without further details on the requirements. You could annotate your super classes with the arguments
and get the super class of the method parameter types during iteration with
cls.getSuperClass()and retrieve the annotated argument value afterwards for assignment.