Example usage for org.apache.commons.beanutils MethodUtils getMatchingAccessibleMethod

List of usage examples for org.apache.commons.beanutils MethodUtils getMatchingAccessibleMethod

Introduction

In this page you can find the example usage for org.apache.commons.beanutils MethodUtils getMatchingAccessibleMethod.

Prototype

public static Method getMatchingAccessibleMethod(Class clazz, String methodName, Class[] parameterTypes) 

Source Link

Document

Find an accessible method that matches the given name and has compatible parameters.

Usage

From source file:com.curl.orb.servlet.InstanceManagementUtil.java

/**
 * Get Method.// w w w  .  j a  va2  s .  co  m
 */
public static Method getMethod(Object obj, String methodName, Object[] arguments) throws NoSuchMethodException {
    Method method = MethodUtils.getMatchingAccessibleMethod(obj.getClass(), methodName,
            getArgumentClasses(arguments));
    if (method == null)
        throw new NoSuchMethodException("No such accessible method: " + methodName + "() on object");
    return method;
}

From source file:com.smhumayun.mi_plus.impl.MIMethodResolverImpl.java

/**
 * Resolve method based on following strategy:
 * - Iterate over composed objects (order will be the same as defined in {@link com.smhumayun.mi_plus.MISupport}
 * - For each composed object, check if there's a matching 'accessible' method based on the algorithm defined by
 * {@link MethodUtils#getAccessibleMethod(Class, String, Class[])} i.e. it finds 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./*from  ww w  . j  a v  a  2s . c  o  m*/
 * - If a match is found, break the iteration and exit from the loop;
 * - Return the corresponding composed object and the matched method
 *
 * @param miContainerClass      MI Container class
 * @param composedObjects       map of composed objects
 * @param methodCall            method call made on Proxy
 * @param methodCallArgs        method call arguments
 * @return resolved target method and object
 * @throws com.smhumayun.mi_plus.MIException {@link com.smhumayun.mi_plus.MIException}
 */
public Pair<Object, Method> resolve(Class miContainerClass, LinkedHashMap<Class, Object> composedObjects,
        Method methodCall, Object[] methodCallArgs) throws MIException {
    logger.info("resolve " + methodCall.toGenericString());
    Class[] methodCallArgsClasses = utils.getClasses(methodCallArgs);
    logger.fine("methodCallArgs classes = " + Arrays.toString(methodCallArgsClasses));
    Object targetObject = null;
    Method targetMethod = null;
    for (Class composedObjectClass : composedObjects.keySet()) {
        try {
            targetMethod = MethodUtils.getMatchingAccessibleMethod(composedObjectClass, methodCall.getName(),
                    methodCallArgsClasses);
            if (targetMethod != null) {
                logger.info("matching method found! " + targetMethod.toGenericString());
                targetObject = composedObjects.get(composedObjectClass);
                break;
            }
        } catch (Exception e) {
            /* SWALLOW */ }
    }
    //if not found
    if (targetMethod == null)
        //throw exception
        throw new UnsupportedOperationException("method '" + methodCall.toGenericString() + "' not found");
    //else return the target object and method to caller
    return new Pair<Object, Method>(targetObject, targetMethod);
}

From source file:com.curl.orb.servlet.InstanceManagementUtil.java

/**
 * Get static Method.// w  ww.  j  a v a  2  s.  com
 */
public static Method getStaticMethod(Class<?> cls, String methodName, Object[] arguments)
        throws NoSuchMethodException {
    Method method = MethodUtils.getMatchingAccessibleMethod(cls, methodName, getArgumentClasses(arguments));
    if (method == null)
        throw new NoSuchMethodException("No such accessible method: " + methodName + "() on object");
    return method;
}

From source file:net.sf.qooxdoo.rpc.RpcServlet.java

/**
 * Looks up an instance of a service and creates one if necessary.
 *
 * @param   session             the current session (for storing
 *                              instances).
 * @param   serviceClassName    the fully qualified name of the class
 *                              to instantiate.
 * @param   name                the name to use for the instance.
 * @param   requiredType        The type the service must have. May be
 *                              null. /*w  w  w .  j  a  va  2  s .  c om*/
 */

public synchronized Service getServiceInstance(HttpSession session, String serviceClassName, Object name,
        Class requiredType) throws ClassNotFoundException, IllegalAccessException, InstantiationException,
        InvocationTargetException, NoSuchMethodException {

    if (requiredType == null) {
        requiredType = Service.class;
    }

    String lookFor = serviceClassName;
    if (name != null) {
        lookFor += "/" + name;
    }
    Service inst = (Service) session.getAttribute(lookFor);
    if (inst == null) {
        Class clazz = Class.forName(serviceClassName);
        if (!requiredType.isAssignableFrom(clazz)) {
            throw new ClassCastException("The requested service class " + clazz.getName()
                    + " is not from the required type " + requiredType.getName() + "");
        }
        inst = (Service) clazz.newInstance();
        Class[] paramTypes = new Class[1];
        Object[] params = new Object[1];
        paramTypes[0] = Environment.class;
        Method method = MethodUtils.getMatchingAccessibleMethod(clazz, "setWebcomponentEnvironment",
                paramTypes);
        if (method == null) {
            method = MethodUtils.getMatchingAccessibleMethod(clazz, "setQooxdooEnvironment", paramTypes);
        }
        if (method != null) {
            params[0] = new Environment();
            method.invoke(inst, params);
        }
        if (name != null) {
            paramTypes[0] = String.class;
            method = MethodUtils.getMatchingAccessibleMethod(clazz, "setWebcomponentName", paramTypes);
            if (method != null) {
                params[0] = name;
                method.invoke(inst, params);
            }
        }
        session.setAttribute(lookFor, inst);

        // initialize the service properties
        ServletConfig servletConfig = getServletConfig();
        Enumeration initParamNames = servletConfig.getInitParameterNames();
        String initParamName;
        String initParamValue;
        int pos;
        String packageName;
        String propertyName;
        HashMap candidates = new HashMap();
        while (initParamNames.hasMoreElements()) {
            initParamName = (String) initParamNames.nextElement();
            pos = initParamName.lastIndexOf('.');
            if (pos == -1) {
                packageName = "";
                propertyName = initParamName;
            } else {
                packageName = initParamName.substring(0, pos);
                propertyName = initParamName.substring(pos + 1);
            }
            String candidateName;
            if (serviceClassName.startsWith(packageName)) {
                candidateName = (String) candidates.get(propertyName);
                if (candidateName == null) {
                    candidates.put(propertyName, initParamName);
                } else if (candidateName.length() < initParamName.length()) {
                    candidates.put(propertyName, initParamName);
                }
            }
        }
        Iterator candidatesIterator = candidates.keySet().iterator();
        Class propertyType;
        while (candidatesIterator.hasNext()) {
            propertyName = (String) candidatesIterator.next();
            initParamName = (String) candidates.get(propertyName);
            initParamValue = servletConfig.getInitParameter(initParamName);
            propertyType = PropertyUtils.getPropertyType(inst, propertyName);
            if (propertyType != null) {
                if (propertyType.getComponentType() == String.class) {
                    PropertyUtils.setSimpleProperty(inst, propertyName,
                            StringUtils.tokenize(initParamValue, ';'));
                } else {
                    try {
                        PropertyUtils.setSimpleProperty(inst, propertyName,
                                ConvertUtils.convert(initParamValue, propertyType));
                    } catch (Exception e) {
                        // try to instatiate a class of the supplied parameter
                        //System.out.println("***** setting '" + propertyName + "' to an instance of '" + initParamValue + "'");
                        PropertyUtils.setSimpleProperty(inst, propertyName,
                                getServiceInstance(session, initParamValue, null, null));
                    }
                }
            } else {
                //System.out.println("***** property '" + propertyName + "' not matched");
            }
        }

        // tell the instance that we're done
        paramTypes = new Class[0];
        method = MethodUtils.getMatchingAccessibleMethod(clazz, "webcomponentInit", paramTypes);
        if (method != null) {
            params = new Object[0];
            method.invoke(inst, params);
        }
    }
    return inst;
}

From source file:com.abstratt.mdd.internal.frontend.textuml.TextUMLFormatter.java

/**
 * Tries to find a more specific formatter for the given node type. If none
 * can be found, falls back to the generic formatter.
 * //w w w  . j  a  v a 2 s.c om
 * @param node
 * @param output
 * @param indentation
 */
private void format(Node node, StringBuilder output, int indentation) {
    if (node == null)
        return;
    if (!formatters.containsKey(node.getClass())) {
        Method method = MethodUtils.getMatchingAccessibleMethod(this.getClass(), "format",
                new Class[] { node.getClass(), StringBuilder.class, Integer.class });
        formatters.put(node.getClass(), method);
    }
    Method formatterMethod = formatters.get(node.getClass());
    if (formatterMethod == null) {
        doGenericFormat(node, output, indentation);
        return;
    }
    try {
        formatterMethod.invoke(this, new Object[] { node, output, indentation });
    } catch (IllegalArgumentException e) {
        LogUtils.logError(TextUMLCore.PLUGIN_ID, "Unexpected  exception", e);
    } catch (IllegalAccessException e) {
        LogUtils.logError(TextUMLCore.PLUGIN_ID, "Unexpected  exception", e);
    } catch (InvocationTargetException e) {
        LogUtils.logError(TextUMLCore.PLUGIN_ID, "Unexpected  exception", e);
    }
}

From source file:org.ajax4jsf.templatecompiler.builder.AbstractCompilationContext.java

public Class<?> getMethodReturnedClass(Class<?> clazz, String methodName, Class<?>[] parametersTypes)
        throws NoSuchMethodException {
    Class<?> returnedType = null;
    log.debug("class : " + clazz.getName() + "\n\t method : " + methodName + "\n\t paramTypes : "
            + Arrays.asList(parametersTypes).toString());

    Method method = MethodUtils.getMatchingAccessibleMethod(clazz, methodName, parametersTypes);

    if (null != method) {
        returnedType = method.getReturnType();
        log.debug("Method found, return type : " + returnedType.getName());

        return returnedType;
    } else {/*from  w  w w  .ja  v a2 s.  c o m*/
        throw new NoSuchMethodException(
                clazz + "#" + methodName + "(" + Arrays.toString(parametersTypes) + ")");
    }

}

From source file:org.bonitasoft.engine.commons.JavaMethodInvoker.java

public Object invokeJavaMethod(final String typeOfValueToSet, final Object valueToSetObjectWith,
        final Object objectToInvokeJavaMethodOn, final String operator, final String operatorParameterClassName)
        throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, IllegalArgumentException,
        InvocationTargetException {
    final Class<?> expressionResultType = getClassOrPrimitiveClass(typeOfValueToSet);
    final Class<?> dataType = Thread.currentThread().getContextClassLoader()
            .loadClass(objectToInvokeJavaMethodOn.getClass().getName());
    final Method method = MethodUtils.getMatchingAccessibleMethod(dataType, operator,
            new Class[] { getClassOrPrimitiveClass(operatorParameterClassName) });
    final Object o = dataType.cast(objectToInvokeJavaMethodOn);
    method.invoke(o, expressionResultType.cast(valueToSetObjectWith));
    return o;/*  w  ww .j  a va2  s  . com*/
}

From source file:org.diffkit.util.DKObjectUtil.java

@SuppressWarnings("rawtypes")
public static boolean respondsTo(Object target_, String methodName_, Class[] parmTypes_) {
    if ((target_ == null) || (methodName_ == null))
        return false;
    if (parmTypes_ == null)
        parmTypes_ = new Class[0];
    Method method = MethodUtils.getMatchingAccessibleMethod(target_.getClass(), methodName_, parmTypes_);
    return (method != null);
}

From source file:org.jspresso.framework.util.accessor.bean.BeanCollectionAccessor.java

/**
 * {@inheritDoc}/*from w  w w .j  a  v a 2 s.c  om*/
 */
@Override
public void addToValue(Object target, Object value) throws IllegalAccessException, InvocationTargetException {
    if (adderMethod == null) {
        adderMethod = MethodUtils.getMatchingAccessibleMethod(getBeanClass(),
                AccessorInfo.ADDER_PREFIX + capitalizeFirst(getProperty()),
                new Class<?>[] { getElementClass() });
    }
    try {
        adderMethod.invoke(getLastNestedTarget(target, getProperty()), value);
    } catch (InvocationTargetException ex) {
        if (ex.getCause() instanceof RuntimeException) {
            throw (RuntimeException) ex.getCause();
        }
        throw ex;
    } catch (IllegalArgumentException | NoSuchMethodException ex) {
        throw new RuntimeException(ex);
    }
}

From source file:org.jspresso.framework.util.accessor.bean.BeanCollectionAccessor.java

/**
 * {@inheritDoc}/* w w  w  .  j a  v  a2 s . com*/
 */
@Override
public void removeFromValue(Object target, Object value)
        throws IllegalAccessException, InvocationTargetException {
    if (removerMethod == null) {
        removerMethod = MethodUtils.getMatchingAccessibleMethod(getBeanClass(),
                AccessorInfo.REMOVER_PREFIX + capitalizeFirst(getProperty()),
                new Class<?>[] { getElementClass() });
    }
    try {
        removerMethod.invoke(getLastNestedTarget(target, getProperty()), value);
    } catch (InvocationTargetException ex) {
        if (ex.getCause() instanceof RuntimeException) {
            throw (RuntimeException) ex.getCause();
        }
        throw ex;
    } catch (IllegalArgumentException | NoSuchMethodException ex) {
        throw new RuntimeException(ex);
    }
}