Android examples for java.lang.reflect:Method
search the method and return the defined method.
//package com.java2s; import java.lang.reflect.Method; import java.lang.reflect.Modifier; public class Main { /**/*from w ww . ja v a 2s .c om*/ * search the method and return the defined method.{@link #searchMethod(Class, String, Class[], boolean)} */ public static Method searchMethod(Class<?> currentClass, String name, Class<?>[] parameterTypes) throws NoSuchMethodException { return searchMethod(currentClass, name, parameterTypes, false); } /** * search the method and return the defined method. * it will {@link Class#getMethod(String, Class[])}, if exception occurs, * it will search for all methods, and find the most fit method. */ public static Method searchMethod(Class<?> currentClass, String name, Class<?>[] parameterTypes, boolean boxed) throws NoSuchMethodException { if (currentClass == null) { throw new NoSuchMethodException("class == null"); } try { return currentClass.getMethod(name, parameterTypes); } catch (NoSuchMethodException e) { Method likeMethod = null; for (Method method : currentClass.getMethods()) { if (method.getName().equals(name) && parameterTypes.length == method .getParameterTypes().length && Modifier.isPublic(method.getModifiers())) { if (parameterTypes.length > 0) { Class<?>[] types = method.getParameterTypes(); boolean eq = true; boolean like = true; for (int i = 0; i < parameterTypes.length; i++) { Class<?> type = types[i]; Class<?> parameterType = parameterTypes[i]; if (type != null && parameterType != null && !type.equals(parameterType)) { eq = false; if (boxed) { type = getBoxedClass(type); parameterType = getBoxedClass(parameterType); } if (!type.isAssignableFrom(parameterType)) { eq = false; like = false; break; } } } if (!eq) { if (like && (likeMethod == null || likeMethod .getParameterTypes()[0] .isAssignableFrom(method .getParameterTypes()[0]))) { likeMethod = method; } continue; } } return method; } } if (likeMethod != null) { return likeMethod; } throw e; } } /** * get boxed type of class */ public static Class<?> getBoxedClass(Class<?> type) { if (type == boolean.class) { return Boolean.class; } else if (type == char.class) { return Character.class; } else if (type == byte.class) { return Byte.class; } else if (type == short.class) { return Short.class; } else if (type == int.class) { return Integer.class; } else if (type == long.class) { return Long.class; } else if (type == float.class) { return Float.class; } else if (type == double.class) { return Double.class; } else { return type; } } }