Java Code Examples for org.apache.commons.lang.ClassUtils

The following examples show how to use org.apache.commons.lang.ClassUtils. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
private TimelineMetric createTimelineMetric(long currentTimeMillis, String component, String attributeName,
    Number attributeValue) {
  if (LOG.isTraceEnabled()) {
    LOG.trace("Creating timeline metric: " + attributeName + " = " + attributeValue + " time = "
        + currentTimeMillis + " app_id = " + component);
  }
  TimelineMetric timelineMetric = new TimelineMetric();
  timelineMetric.setMetricName(attributeName);
  timelineMetric.setHostName(hostname);
  if (setInstanceId) {
    timelineMetric.setInstanceId(instanceId);
  }
  timelineMetric.setAppId(component);
  timelineMetric.setStartTime(currentTimeMillis);
  timelineMetric.setType(ClassUtils.getShortCanonicalName(attributeValue, "Number"));
  timelineMetric.getMetricValues().put(currentTimeMillis, attributeValue.doubleValue());
  return timelineMetric;
}
 
Example 2
/**
 * Returns whether or not to append the given <code>Field</code>.
 * <ul>
 * <li>Transient fields are appended only if {@link #isAppendTransients()} returns <code>true</code>.
 * <li>Static fields are appended only if {@link #isAppendStatics()} returns <code>true</code>.
 * <li>Inner class fields are not appened.</li>
 * </ul>
 * 
 * @param field
 *            The Field to test.
 * @return Whether or not to append the given <code>Field</code>.
 */
protected boolean accept(Field field) {
    if (field.getName().indexOf(ClassUtils.INNER_CLASS_SEPARATOR_CHAR) != -1) {
        // Reject field from inner class.
        return false;
    }
    if (Modifier.isTransient(field.getModifiers()) && !this.isAppendTransients()) {
        // Reject transient fields.
        return false;
    }
    if (Modifier.isStatic(field.getModifiers()) && !this.isAppendStatics()) {
        // Reject static fields.
        return false;
    }
    if (this.getExcludeFieldNames() != null
        && Arrays.binarySearch(this.getExcludeFieldNames(), field.getName()) >= 0) {
        // Reject fields from the getExcludeFieldNames list.
        return false;
    }
    return true;
}
 
Example 3
Source Project: mycore   Source File: MCRFunctionCallJava.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
public Object call(Context context, List args) throws FunctionCallException {
    try {
        String clazzName = (String) (args.get(0));
        String methodName = (String) (args.get(1));
        LOGGER.debug("XEditor extension function calling {} {}", clazzName, methodName);

        Class[] argTypes = new Class[args.size() - 2];
        Object[] params = new Object[args.size() - 2];
        for (int i = 0; i < argTypes.length; i++) {
            argTypes[i] = args.get(i + 2).getClass();
            params[i] = args.get(i + 2);
        }

        Class clazz = ClassUtils.getClass(clazzName);
        Method method = MethodUtils.getMatchingAccessibleMethod(clazz, methodName, argTypes);
        return method.invoke(null, params);
    } catch (Exception ex) {
        LOGGER.warn("Exception in call to external java method", ex);
        return ex.getMessage();
    }
}
 
Example 4
Source Project: jdal   Source File: ConfigurableFieldFactory.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings({ "unchecked", "rawtypes" })
protected Object findByClass(Class<?> clazz, Map<Class<?>, ?> map) {
	Object target;
	target = map.get(clazz);
	
	if (target == null) { // try with superclasses
		List superclasses = ClassUtils.getAllSuperclasses(clazz);
		superclasses.addAll(ClassUtils.getAllInterfaces(clazz));
		Iterator iter = superclasses.iterator();
	
		while (iter.hasNext() && target == null)  {
			target = map.get(iter.next());
		}
	}
	
	return target;
}
 
Example 5
Source Project: projectforge-webapp   Source File: XmlDump.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * @param field
 * @return true, if the given field should be compared.
 */
protected boolean accept(final Field field)
{
  if (field.getName().indexOf(ClassUtils.INNER_CLASS_SEPARATOR_CHAR) != -1) {
    // Reject field from inner class.
    return false;
  }
  if (field.getName().equals("handler") == true) {
    // Handler of Javassist proxy should be ignored.
    return false;
  }
  if (Modifier.isTransient(field.getModifiers()) == true) {
    // transients.
    return false;
  }
  if (Modifier.isStatic(field.getModifiers()) == true) {
    // transients.
    return false;
  }
  return true;
}
 
Example 6
/**
 * Returns whether or not to append the given <code>Field</code>.
 * <ul>
 * <li>Ignore transient fields
 * <li>Ignore static fields
 * <li>Ignore inner class fields</li>
 * </ul>
 * 
 * @param field The Field to test.
 * @return Whether or not to consider the given <code>Field</code>.
 */
protected static boolean accept(final Field field)
{
  if (field.getName().indexOf(ClassUtils.INNER_CLASS_SEPARATOR_CHAR) != -1) {
    // Reject field from inner class.
    return false;
  }
  if (Modifier.isTransient(field.getModifiers()) == true) {
    // transients.
    return false;
  }
  if (Modifier.isStatic(field.getModifiers()) == true) {
    // transients.
    return false;
  }
  return true;
}
 
Example 7
Source Project: gama   Source File: GamaBasicTypeConverter.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
public boolean canConvert(final Class arg0) {
	final List<Class<?>> allClassesApa = ClassUtils.getAllSuperclasses(arg0);
	for (final Object c : allClassesApa) {
		if (c.equals(GamaType.class))
			return true;
	}
	// if((arg0.equals(GamaType.class)) ||
	// (arg0.getSuperclass().equals(GamaType.class)))
	// {return true;}

	// List allInterfaceApa = ClassUtils.getAllInterfaces(arg0);
	//
	// for(Object i : allInterfaceApa) {
	// if(i.equals(IType.class))
	// return true;
	// }
	return false;
}
 
Example 8
Source Project: metron   Source File: MultiIndexDao.java    License: Apache License 2.0 6 votes vote down vote up
private DocumentContainer addCommentToAlert(IndexDao indexDao, CommentAddRemoveRequest request, Document latest) {
  DocumentContainer container;
  try {
    Document document = indexDao.addCommentToAlert(request, latest);
    container = new DocumentContainer(document);
    LOG.debug("Added comment to alert; indexDao={}, guid={}, sensorType={}, document={}",
            ClassUtils.getShortClassName(indexDao.getClass()), document.getGuid(), document.getSensorType(), document);

  } catch (Throwable e) {
    container = new DocumentContainer(e);
    LOG.error("Unable to add comment to alert; indexDao={}, error={}",
            ClassUtils.getShortClassName(indexDao.getClass()), ExceptionUtils.getRootCauseMessage(e));
  }

  return container;
}
 
Example 9
Source Project: metron   Source File: MultiIndexDao.java    License: Apache License 2.0 6 votes vote down vote up
private DocumentContainer removeCommentFromAlert(IndexDao indexDao, CommentAddRemoveRequest request, Document latest) {
  DocumentContainer container;
  try {
    Document document = indexDao.removeCommentFromAlert(request, latest);
    container = new DocumentContainer(document);
    LOG.debug("Removed comment from alert; indexDao={}, guid={}, sensorType={}, document={}",
            ClassUtils.getShortClassName(indexDao.getClass()), document.getGuid(), document.getSensorType(), document);

  } catch (Throwable e) {
    container = new DocumentContainer(e);
    LOG.error("Unable to remove comment from alert; indexDao={}, error={}",
            ClassUtils.getShortClassName(indexDao.getClass()), ExceptionUtils.getRootCauseMessage(e));
  }

  return container;
}
 
Example 10
Source Project: metron   Source File: MultiIndexDao.java    License: Apache License 2.0 6 votes vote down vote up
private DocumentContainer getLatest(IndexDao indexDao, String guid, String sensorType) {
  DocumentContainer container;
  try {
    Document document = indexDao.getLatest(guid, sensorType);
    container = new DocumentContainer(document);
    LOG.debug("Found latest document; indexDao={}, guid={}, sensorType={}, document={}",
            ClassUtils.getShortClassName(indexDao.getClass()), guid, sensorType, document);

  } catch (Throwable e) {
    container = new DocumentContainer(e);
    LOG.error("Unable to find latest document; indexDao={}, error={}",
            ClassUtils.getShortClassName(indexDao.getClass()), ExceptionUtils.getRootCauseMessage(e));
  }

  return container;
}
 
Example 11
/**
 * The field length (if defined by Hibernate). The entity is the target class of the PropertyModel and the field name is the expression of
 * the given PropertyModel.
 * @param model If not from type PropertyModel then null is returned.
 * @return
 */
public static Integer getMaxLength(final IModel<String> model)
{
  Integer length = null;
  if (ClassUtils.isAssignable(model.getClass(), PropertyModel.class)) {
    final PropertyModel< ? > propertyModel = (PropertyModel< ? >) model;
    final Object entity = BeanHelper.getFieldValue(propertyModel, ChainingModel.class, "target");
    if (entity == null) {
      log.warn("Oups, can't get private field 'target' of PropertyModel!.");
    } else {
      final Field field = propertyModel.getPropertyField();
      if (field != null) {
        length = HibernateUtils.getPropertyLength(entity.getClass().getName(), field.getName());
      } else {
        log.info("Can't get field '" + propertyModel.getPropertyExpression() + "'.");
      }
    }
  }
  return length;
}
 
Example 12
/**
 * Returns whether or not to append the given <code>Field</code>.
 * <ul>
 * <li>Ignore transient fields
 * <li>Ignore static fields
 * <li>Ignore inner class fields</li>
 * </ul>
 * 
 * @param field The Field to test.
 * @return Whether or not to consider the given <code>Field</code>.
 */
protected static boolean accept(final Field field)
{
  if (field.getName().indexOf(ClassUtils.INNER_CLASS_SEPARATOR_CHAR) != -1) {
    // Reject field from inner class.
    return false;
  }
  if (Modifier.isTransient(field.getModifiers()) == true) {
    // transients.
    return false;
  }
  if (Modifier.isStatic(field.getModifiers()) == true) {
    // transients.
    return false;
  }
  if ("created".equals(field.getName()) == true || "lastUpdate".equals(field.getName()) == true) {
    return false;
  }
  return true;
}
 
Example 13
/**
 * Returns whether or not to append the given <code>Field</code>.
 * <ul>
 * <li>Transient fields are appended only if {@link #isAppendTransients()} returns <code>true</code>.
 * <li>Static fields are appended only if {@link #isAppendStatics()} returns <code>true</code>.
 * <li>Inner class fields are not appened.</li>
 * </ul>
 * 
 * @param field
 *            The Field to test.
 * @return Whether or not to append the given <code>Field</code>.
 */
protected boolean accept(Field field) {
    if (field.getName().indexOf(ClassUtils.INNER_CLASS_SEPARATOR_CHAR) != -1) {
        // Reject field from inner class.
        return false;
    }
    if (Modifier.isTransient(field.getModifiers()) && !this.isAppendTransients()) {
        // Reject transient fields.
        return false;
    }
    if (Modifier.isStatic(field.getModifiers()) && !this.isAppendStatics()) {
        // Rject static fields.
        return false;
    }
    if (this.getExcludeFieldNames() != null
        && Arrays.binarySearch(this.getExcludeFieldNames(), field.getName()) >= 0) {
        // Reject fields from the getExcludeFieldNames list.
        return false;
    }
    return true;
}
 
Example 14
/**
 * Copies all values from the given src object excluding the values created and lastUpdate. Do not overwrite created and lastUpdate from
 * the original database object.
 * @param src
 * @param dest
 * @param ignoreFields Does not copy these properties (by field name).
 * @return true, if any modifications are detected, otherwise false;
 */
@SuppressWarnings("unchecked")
public static ModificationStatus copyValues(final BaseDO src, final BaseDO dest, final String... ignoreFields)
{
  if (ClassUtils.isAssignable(src.getClass(), dest.getClass()) == false) {
    throw new RuntimeException("Try to copyValues from different BaseDO classes: this from type "
        + dest.getClass().getName()
        + " and src from type"
        + src.getClass().getName()
        + "!");
  }
  if (src.getId() != null && (ignoreFields == null || ArrayUtils.contains(ignoreFields, "id") == false)) {
    dest.setId(src.getId());
  }
  return copyDeclaredFields(src.getClass(), src, dest, ignoreFields);
}
 
Example 15
/**
 * Logs the user in, if not already logged-in. If an user is already logged in then nothing is done. Therefore you must log-out an user
 * before any new login.
 * @param username
 * @param password not encrypted.
 */
public void login(final String username, final String password, final boolean checkDefaultPage)
{
  // start and render the test page
  tester.startPage(LoginPage.class);
  if (ClassUtils.isAssignable(tester.getLastRenderedPage().getClass(), WicketUtils.getDefaultPage()) == true) {
    // Already logged-in.
    return;
  }
  // assert rendered page class
  tester.assertRenderedPage(LoginPage.class);
  final FormTester form = tester.newFormTester("body:form");
  form.setValue(findComponentByLabel(form, "username"), username);
  form.setValue(findComponentByLabel(form, "password"), password);
  form.submit(KEY_LOGINPAGE_BUTTON_LOGIN);
  if (checkDefaultPage == true) {
    tester.assertRenderedPage(WicketUtils.getDefaultPage());
  }
}
 
Example 16
Source Project: rice   Source File: RichTable.java    License: Educational Community License v2.0 6 votes vote down vote up
private String getSortType(Class<?> dataTypeClass) {
    String sortType = UifConstants.TableToolsValues.STRING;
    if (ClassUtils.isAssignable(dataTypeClass, KualiPercent.class)) {
        sortType = UifConstants.TableToolsValues.PERCENT;
    } else if (ClassUtils.isAssignable(dataTypeClass, KualiInteger.class) || ClassUtils.isAssignable(dataTypeClass,
            KualiDecimal.class)) {
        sortType = UifConstants.TableToolsValues.CURRENCY;
    } else if (ClassUtils.isAssignable(dataTypeClass, Timestamp.class)) {
        sortType = "date";
    } else if (ClassUtils.isAssignable(dataTypeClass, java.sql.Date.class) || ClassUtils.isAssignable(dataTypeClass,
            java.util.Date.class)) {
        sortType = UifConstants.TableToolsValues.DATE;
    } else if (ClassUtils.isAssignable(dataTypeClass, Number.class)) {
        sortType = UifConstants.TableToolsValues.NUMERIC;
    }
    return sortType;
}
 
Example 17
private void injectWebMembers() throws Exception {
       DelegationRulesProxy delegationRulesProxy = new DelegationRulesProxy(getDelegationRules());
       Class delegationRulesClass = getDelegationRules().getClass();
       //System.err.println("delegation rules class: "+ delegationRulesClass);
       Class[] delegationRulesInterfaces = new Class[0]; // = delegationRulesClass.getInterfaces();
       List<Class> delegationRulesInterfaceList = (List<Class>) ClassUtils.getAllInterfaces(delegationRulesClass);
       delegationRulesInterfaces = delegationRulesInterfaceList.toArray(delegationRulesInterfaces);
       ClassLoader delegationRulesClassLoader = getDelegationRules().getClass().getClassLoader();
       Object o = Proxy.newProxyInstance(delegationRulesClassLoader, delegationRulesInterfaces, delegationRulesProxy);
       //setDelegationRules((List) o);

	if (Integer.parseInt(CoreFrameworkServiceLocator.getParameterService().getParameterValueAsString(KewApiConstants.KEW_NAMESPACE, KRADConstants.DetailTypes.RULE_DETAIL_TYPE, KewApiConstants.RULE_DELEGATE_LIMIT)) > getDelegationRules().size() || showDelegations) {
		for (Iterator iterator = getDelegationRules().iterator(); iterator.hasNext();) {
			RuleDelegationBo ruleDelegation = (RuleDelegationBo) iterator.next();
			WebRuleBaseValues webRule = new WebRuleBaseValues();
			webRule.load(ruleDelegation.getDelegationRule());
			webRule.edit(ruleDelegation.getDelegationRule());
			ruleDelegation.setDelegationRule(webRule);
		}
	}
}
 
Example 18
Source Project: rice   Source File: AnnotationHelper.java    License: Educational Community License v2.0 6 votes vote down vote up
private AnnotationExpr findAnnotation(final BodyDeclaration n, String fullyQualifiedName, boolean foundAnnImport) {
    final String simpleName = ClassUtils.getShortClassName(fullyQualifiedName);
    final List<AnnotationExpr> annotations = n.getAnnotations() != null ? n.getAnnotations() : new ArrayList<AnnotationExpr>();

    for (AnnotationExpr ae : annotations) {
        final String name = ae.getName().toString();
        if ((simpleName.equals(name) && foundAnnImport)) {
            LOG.info("found " + ae + " on " + getTypeOrFieldNameForMsg(n) + ".");
            return ae;
        }

        if (fullyQualifiedName.equals(name)) {
            LOG.info("found " + ae + " on " + getTypeOrFieldNameForMsg(n) + ".");
            return ae;
        }
    }
    return null;
}
 
Example 19
Source Project: rice   Source File: AnnotationHelper.java    License: Educational Community License v2.0 6 votes vote down vote up
private boolean imported(List<ImportDeclaration> imports, String fullyQualifiedName) {
    final String packageName = ClassUtils.getPackageName(fullyQualifiedName);

    for (final ImportDeclaration i : imports) {
        if (!i.isStatic()) {
            final String importName = i.getName().toString();
            if (i.isAsterisk()) {
                if (packageName.equals(importName)) {
                    if ( LOG.isDebugEnabled() ) {
                        LOG.debug("found import " + packageName + ".* on " + getTypeNameForMsg(i) + ".");
                    }
                    return true;
                }
            } else {
                if (fullyQualifiedName.equals(importName)) {
                    if ( LOG.isDebugEnabled() ) {
                        LOG.debug("found import " + fullyQualifiedName + " on " + getTypeNameForMsg(i) + ".");
                    }
                    return true;
                }
            }
        }
    }
    return false;
}
 
Example 20
private void check(final HttpSession session, final String name, final Object value)
{
  if (log.isInfoEnabled()) {
    try {
      if (log.isDebugEnabled()) {
        log
        .debug("Storing "
            + ClassUtils.getShortClassName(value, "null")
            + " under the name "
            + name
            + " in session "
            + session.getId());
      }
      final ByteArrayOutputStream baos = new ByteArrayOutputStream();
      final ObjectOutputStream oos = new ObjectOutputStream(baos);
      oos.writeObject(value);
      oos.close();
      final ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray()));
      ois.readObject();
    } catch (final Exception ex) {
      log.warn("Trying to store non-serializable value " + value + " under the name " + name + " in session " + session.getId(), ex);
    }
  }
}
 
Example 21
Source Project: hop   Source File: DisplayInvocationHandler.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings( "unchecked" )
public static <T> T forObject( Class<T> iface, T delegate, Display display, ILogChannel log,
                               boolean asyncForVoid ) {
  return (T) Proxy.newProxyInstance( delegate.getClass().getClassLoader(), (Class<?>[]) ClassUtils.getAllInterfaces(
    delegate.getClass() ).toArray( new Class<?>[] {} ), new DisplayInvocationHandler<T>( display, delegate, log,
    asyncForVoid ) );
}
 
Example 22
Source Project: sofa-acts   Source File: ReflectUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 
 * @param className
 * @return
 */
public static Class<?> getClassForName(String className) {
    try {
        return ClassUtils.getClass(className);
    } catch (Exception e) {
        throw new RuntimeException(e.getMessage(), e);
    }

}
 
Example 23
Source Project: prong-uid   Source File: NamingThreadFactory.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Get the method invoker's class name
 * 
 * @param depth
 * @return
 */
private String getInvoker(int depth) {
    Exception e = new Exception();
    StackTraceElement[] stes = e.getStackTrace();
    if (stes.length > depth) {
        return ClassUtils.getShortClassName(stes[depth].getClassName());
    }
    return getClass().getSimpleName();
}
 
Example 24
Source Project: rebuild   Source File: StateHelper.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * 加载状态枚举类
 *
 * @param stateClass
 * @return
 * @throws IllegalArgumentException
 */
public static Class<?> getSatetClass(String stateClass) throws IllegalArgumentException {
    Assert.notNull(stateClass, "[stateClass] not be null");

    Class<?> stateEnum;
    try {
        stateEnum = ClassUtils.getClass(stateClass);
        if (stateEnum.isEnum() && ClassUtils.isAssignable(stateEnum, StateSpec.class)) {
            return stateEnum;
        }
    } catch (ClassNotFoundException ignored) {
        throw new IllegalArgumentException("No class of state found: " + stateClass);
    }
    throw new IllegalArgumentException("Bad class of state found: " + stateEnum);
}
 
Example 25
Source Project: uid-generator   Source File: NamingThreadFactory.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Get the method invoker's class name
 * 
 * @param depth
 * @return
 */
private String getInvoker(int depth) {
    Exception e = new Exception();
    StackTraceElement[] stes = e.getStackTrace();
    if (stes.length > depth) {
        return ClassUtils.getShortClassName(stes[depth].getClassName());
    }
    return getClass().getSimpleName();
}
 
Example 26
Source Project: usergrid   Source File: ApiResponse.java    License: Apache License 2.0 5 votes vote down vote up
public static String exceptionToErrorCode( Throwable e ) {
    if ( e == null ) {
        return "service_error";
    }
    String s = ClassUtils.getShortClassName( e.getClass() );
    s = StringUtils.removeEnd( s, "Exception" );
    s = InflectionUtils.underscore( s ).toLowerCase();
    return s;
}
 
Example 27
Source Project: lams   Source File: ValuedEnum.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * <p>Human readable description of this <code>Enum</code> item.</p>
 *
 * @return String in the form <code>type[name=value]</code>, for example:
 *  <code>JavaVersion[Java 1.0=100]</code>. Note that the package name is
 *  stripped from the type name.
 */
public String toString() {
    if (iToString == null) {
        String shortName = ClassUtils.getShortClassName(getEnumClass());
        iToString = shortName + "[" + getName() + "=" + getValue() + "]";
    }
    return iToString;
}
 
Example 28
Source Project: lams   Source File: Enum.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * <p>Human readable description of this Enum item.</p>
 * 
 * @return String in the form <code>type[name]</code>, for example:
 * <code>Color[Red]</code>. Note that the package name is stripped from
 * the type name.
 */
public String toString() {
    if (iToString == null) {
        String shortName = ClassUtils.getShortClassName(getEnumClass());
        iToString = shortName + "[" + getName() + "]";
    }
    return iToString;
}
 
Example 29
Source Project: lams   Source File: MemberUtils.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Gets the number of steps required needed to turn the source class into
 * the destination class. This represents the number of steps in the object
 * hierarchy graph.
 * @param srcClass The source class
 * @param destClass The destination class
 * @return The cost of transforming an object
 */
private static float getObjectTransformationCost(Class srcClass, Class destClass) {
    if (destClass.isPrimitive()) {
        return getPrimitivePromotionCost(srcClass, destClass);
    }
    float cost = 0.0f;
    while (srcClass != null && !destClass.equals(srcClass)) {
        if (destClass.isInterface() && ClassUtils.isAssignable(srcClass, destClass)) {
            // slight penalty for interface match.
            // we still want an exact match to override an interface match,
            // but
            // an interface match should override anything where we have to
            // get a superclass.
            cost += 0.25f;
            break;
        }
        cost++;
        srcClass = srcClass.getSuperclass();
    }
    /*
     * If the destination class is null, we've travelled all the way up to
     * an Object match. We'll penalize this by adding 1.5 to the cost.
     */
    if (srcClass == null) {
        cost += 1.5f;
    }
    return cost;
}
 
Example 30
Source Project: lams   Source File: MethodUtils.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * <p>Find an accessible method that matches the given name and has compatible parameters.
 * Compatible parameters mean that every method parameter is assignable from 
 * the given parameters.
 * In other words, it finds a method with the given name 
 * that will take the parameters given.<p>
 *
 * <p>This method is used by 
 * {@link 
 * #invokeMethod(Object object, String methodName, Object[] args, Class[] parameterTypes)}.
 *
 * <p>This method can match primitive parameter by passing in wrapper classes.
 * For example, a <code>Boolean</code> will match a primitive <code>boolean</code>
 * parameter.
 *
 * @param cls find method in this class
 * @param methodName find method with this name
 * @param parameterTypes find method with most compatible parameters 
 * @return The accessible method
 */
public static Method getMatchingAccessibleMethod(Class cls,
        String methodName, Class[] parameterTypes) {
    try {
        Method method = cls.getMethod(methodName, parameterTypes);
        MemberUtils.setAccessibleWorkaround(method);
        return method;
    } catch (NoSuchMethodException e) { /* SWALLOW */
    }
    // search through all methods
    Method bestMatch = null;
    Method[] methods = cls.getMethods();
    for (int i = 0, size = methods.length; i < size; i++) {
        if (methods[i].getName().equals(methodName)) {
            // compare parameters
            if (ClassUtils.isAssignable(parameterTypes, methods[i]
                    .getParameterTypes(), true)) {
                // get accessible version of method
                Method accessibleMethod = getAccessibleMethod(methods[i]);
                if (accessibleMethod != null) {
                    if (bestMatch == null
                            || MemberUtils.compareParameterTypes(
                                    accessibleMethod.getParameterTypes(),
                                    bestMatch.getParameterTypes(),
                                    parameterTypes) < 0) {
                        bestMatch = accessibleMethod;
                    }
                }
            }
        }
    }
    if (bestMatch != null) {
        MemberUtils.setAccessibleWorkaround(bestMatch);
    }
    return bestMatch;
}