diff --git a/NCPCommons/src/main/java/fr/neatmonster/nocheatplus/utilities/ReflectionUtil.java b/NCPCommons/src/main/java/fr/neatmonster/nocheatplus/utilities/ReflectionUtil.java index 8a97c65c..51135342 100644 --- a/NCPCommons/src/main/java/fr/neatmonster/nocheatplus/utilities/ReflectionUtil.java +++ b/NCPCommons/src/main/java/fr/neatmonster/nocheatplus/utilities/ReflectionUtil.java @@ -111,7 +111,61 @@ public class ReflectionUtil { public static Object invokeMethodNoArgs(final Object obj, final String methodName, final Class ... returnTypePreference){ // TODO: Isn't there a one-line-call for this ?? final Class objClass = obj.getClass(); - + // Try to get it directly first. + Method methodFound = getMethodNoArgs(objClass, methodName, returnTypePreference); + if (methodFound == null){ + // Fall-back to seek it. + methodFound = seekMethodNoArgs(objClass, methodName, returnTypePreference); + } + // Invoke if found. + if (methodFound != null){ + try{ + final Object res = methodFound.invoke(obj); + return res; + } + catch (Throwable t){ + // TODO: Throw something !? + return null; + } + } + else{ + // TODO: Throw something !? + return null; + } + } + + /** + * Direct getMethod attempt. + * @param objClass + * @param methodName + * @param returnTypePreference + * @return + */ + public static Method getMethodNoArgs(final Class objClass, final String methodName, final Class[] returnTypePreference) { + try { + final Method methodFound = objClass.getMethod(methodName); + if (methodFound != null) { + final Class returnType = methodFound.getReturnType(); + for (int i = 0; i < returnTypePreference.length; i++){ + if (returnType == returnTypePreference[i]){ + return methodFound; + } + } + } + } catch (SecurityException e) { + } catch (NoSuchMethodException e) { + } + return null; + } + + /** + * Iterate over all methods, attempt to return best matching return type (earliest in array). + * @param objClass + * @param methodName + * @param returnTypePreference + * @return + */ + public static Method seekMethodNoArgs(final Class objClass, final String methodName, final Class[] returnTypePreference) { // Collect methods that might work. Method methodFound = null; int returnTypeIndex = returnTypePreference.length; // This can be 0 for no preferences given. @@ -148,20 +202,7 @@ public class ReflectionUtil { } } } - if (methodFound != null){ - try{ - final Object res = methodFound.invoke(obj); - return res; - } - catch (Throwable t){ - // TODO: Throw something !? - return null; - } - } - else{ - // TODO: Throw something !? - return null; - } + return methodFound; } }