Here you can find the source of invokeGenericMethodOneArg(final Object obj, final String methodName, final Object arg)
Parameter | Description |
---|---|
obj | a parameter |
methodName | a parameter |
arg | Argument or invoke the method with. |
public static Object invokeGenericMethodOneArg(final Object obj, final String methodName, final Object arg)
//package com.java2s; //License from project: Open Source License import java.lang.reflect.Method; public class Main { /**//w w w . ja v a 2 s . c om * Dirty method to call a declared method with a generic parameter type. Does try+catch for method invocation and should not throw anything for the normal case. Purpose for this is generic factory registration, having methods with type Object alongside methods with more specialized types. * @param obj * @param methodName * @param arg Argument or invoke the method with. * @return null in case of errors (can not be distinguished). */ public static Object invokeGenericMethodOneArg(final Object obj, final String methodName, final Object arg) { // TODO: Isn't there a one-line-call for this ?? final Class<?> objClass = obj.getClass(); final Class<?> argClass = arg.getClass(); // Collect methods that might work. Method methodFound = null; boolean denyObject = false; for (final Method method : objClass.getDeclaredMethods()) { if (method.getName().equals(methodName)) { final Class<?>[] parameterTypes = method.getParameterTypes(); if (parameterTypes.length == 1) { // Prevent using Object as argument if there exists a method with a specialized argument. if (parameterTypes[0] != Object.class && !parameterTypes[0].isAssignableFrom(argClass)) { denyObject = true; } // Override the found method if none found yet and assignment is possible, or if it has a specialized argument of an already found one. if ((methodFound == null && parameterTypes[0].isAssignableFrom(argClass) || methodFound != null && methodFound.getParameterTypes()[0].isAssignableFrom(parameterTypes[0]))) { methodFound = method; } } } } if (denyObject && methodFound.getParameterTypes()[0] == Object.class) { // TODO: Throw something !? return null; } else if (methodFound != null && methodFound.getParameterTypes()[0].isAssignableFrom(argClass)) { try { final Object res = methodFound.invoke(obj, arg); return res; } catch (Throwable t) { // TODO: Throw something !? return null; } } else { // TODO: Throw something !? return null; } } }