Example usage for java.lang Class getMethods

List of usage examples for java.lang Class getMethods

Introduction

In this page you can find the example usage for java.lang Class getMethods.

Prototype

@CallerSensitive
public Method[] getMethods() throws SecurityException 

Source Link

Document

Returns an array containing Method objects reflecting all the public methods of the class or interface represented by this Class object, including those declared by the class or interface and those inherited from superclasses and superinterfaces.

Usage

From source file:com.google.gwtjsonrpc.server.JsonServlet.java

private static Map<String, MethodHandle> methods(final RemoteJsonService impl) {
    final Class<? extends RemoteJsonService> d = findInterface(impl.getClass());
    if (d == null) {
        return Collections.<String, MethodHandle>emptyMap();
    }/*from   ww  w .jav  a 2s.  c o  m*/

    final Map<String, MethodHandle> r = new HashMap<String, MethodHandle>();
    for (final Method m : d.getMethods()) {
        if (!Modifier.isPublic(m.getModifiers())) {
            continue;
        }

        if (m.getReturnType() != Void.TYPE) {
            continue;
        }

        final Class<?>[] params = m.getParameterTypes();
        if (params.length < 1) {
            continue;
        }

        if (!params[params.length - 1].isAssignableFrom(AsyncCallback.class)) {
            continue;
        }

        final MethodHandle h = new MethodHandle(impl, m);
        r.put(h.getName(), h);
    }
    return Collections.unmodifiableMap(r);
}

From source file:io.github.wysohn.triggerreactor.tools.ReflectionUtil.java

@SuppressWarnings({ "unchecked", "unchecked" })
public static Object invokeMethod(Class<?> clazz, Object obj, String methodName, Object... args)
        throws NoSuchMethodException, IllegalArgumentException, InvocationTargetException,
        IllegalAccessException {//from w ww  .  jav a2s  .  c  o m
    try {
        List<Method> validMethods = new ArrayList<>();

        for (Method method : clazz.getMethods()) {
            Class<?>[] parameterTypes = null;

            if (!method.getName().equals(methodName)) {
                continue;
            }

            parameterTypes = method.getParameterTypes();
            if (method.isVarArgs()) {
                if (method.isVarArgs() && (parameterTypes.length - args.length >= 2)) {
                    parameterTypes = null;
                    continue;
                }
            } else {
                if (parameterTypes.length != args.length) {
                    parameterTypes = null;
                    continue;
                }
            }

            if (method.isVarArgs()) {
                boolean matches = false;

                // check non vararg part
                for (int i = 0; i < parameterTypes.length - 1; i++) {
                    matches = checkMatch(parameterTypes[i], args[i]);
                    if (!matches)
                        break;
                }

                // check rest
                for (int i = parameterTypes.length - 1; i < args.length; i++) {
                    Class<?> arrayType = parameterTypes[parameterTypes.length - 1].getComponentType();

                    matches = checkMatch(arrayType, args[i]);
                    if (!matches)
                        break;
                }

                if (matches) {
                    validMethods.add(method);
                }
            } else {
                boolean matches = true;

                for (int i = 0; i < parameterTypes.length; i++) {
                    matches = checkMatch(parameterTypes[i], args[i]);
                    if (!matches)
                        break;
                }

                if (matches) {
                    validMethods.add(method);
                }
            }
        }

        if (!validMethods.isEmpty()) {
            Method method = validMethods.get(0);
            for (int i = 1; i < validMethods.size(); i++) {
                Method targetMethod = validMethods.get(i);

                Class<?>[] currentParams = method.getParameterTypes();
                Class<?>[] targetParams = targetMethod.getParameterTypes();

                if (method.isVarArgs() && targetMethod.isVarArgs()) {
                    for (int j = 0; j < currentParams.length; j++) {
                        if (currentParams[j].isAssignableFrom(targetParams[j])) {
                            method = targetMethod;
                            break;
                        }
                    }
                } else if (method.isVarArgs()) {
                    //usually, non-vararg is more specific method. So we use that
                    method = targetMethod;
                } else if (targetMethod.isVarArgs()) {
                    //do nothing
                } else {
                    for (int j = 0; j < currentParams.length; j++) {
                        if (targetParams[j].isEnum()) { // enum will be handled later
                            method = targetMethod;
                            break;
                        } else if (ClassUtils.isAssignable(targetParams[j], currentParams[j], true)) { //narrow down to find the most specific method
                            method = targetMethod;
                            break;
                        }
                    }
                }
            }

            method.setAccessible(true);

            for (int i = 0; i < args.length; i++) {
                Class<?>[] parameterTypes = method.getParameterTypes();

                if (args[i] instanceof String && i < parameterTypes.length && parameterTypes[i].isEnum()) {
                    try {
                        args[i] = Enum.valueOf((Class<? extends Enum>) parameterTypes[i], (String) args[i]);
                    } catch (IllegalArgumentException ex1) {
                        // Some overloaded methods already has
                        // String to Enum conversion
                        // So just lets see if one exists
                        Class<?>[] types = new Class<?>[args.length];
                        for (int k = 0; k < args.length; k++)
                            types[k] = args[k].getClass();

                        try {
                            Method alternative = clazz.getMethod(methodName, types);
                            return alternative.invoke(obj, args);
                        } catch (NoSuchMethodException ex2) {
                            throw new RuntimeException(
                                    "Tried to convert value [" + args[i] + "] to Enum [" + parameterTypes[i]
                                            + "] or find appropriate method but found nothing. Make sure"
                                            + " that the value [" + args[i]
                                            + "] matches exactly with one of the Enums in [" + parameterTypes[i]
                                            + "] or the method you are looking exists.");
                        }
                    }
                }
            }

            if (method.isVarArgs()) {
                Class<?>[] parameterTypes = method.getParameterTypes();

                Object varargs = Array.newInstance(parameterTypes[parameterTypes.length - 1].getComponentType(),
                        args.length - parameterTypes.length + 1);
                for (int k = 0; k < Array.getLength(varargs); k++) {
                    Array.set(varargs, k, args[parameterTypes.length - 1 + k]);
                }

                Object[] newArgs = new Object[parameterTypes.length];
                for (int k = 0; k < newArgs.length - 1; k++) {
                    newArgs[k] = args[k];
                }
                newArgs[newArgs.length - 1] = varargs;

                args = newArgs;
            }

            return method.invoke(obj, args);
        }

        if (args.length > 0) {
            StringBuilder builder = new StringBuilder(String.valueOf(args[0].getClass().getSimpleName()));

            for (int i = 1; i < args.length; i++) {
                builder.append(", " + args[i].getClass().getSimpleName());
            }

            throw new NoSuchMethodException(methodName + "(" + builder.toString() + ")");
        } else {
            throw new NoSuchMethodException(methodName + "()");
        }
    } catch (NullPointerException e) {
        StringBuilder builder = new StringBuilder(String.valueOf(args[0]));
        for (int i = 1; i < args.length; i++)
            builder.append("," + String.valueOf(args[i]));
        throw new NullPointerException("Call " + methodName + "(" + builder.toString() + ")");
    }
}

From source file:com.predic8.membrane.annot.bean.MCUtil.java

private static void addXML(Object object, String id, XMLStreamWriter xew, SerializationContext sc)
        throws XMLStreamException {
    if (object == null)
        throw new InvalidParameterException("'object' must not be null.");

    Class<? extends Object> clazz = object.getClass();

    MCElement e = clazz.getAnnotation(MCElement.class);
    if (e == null)
        throw new IllegalArgumentException("'object' must be @MCElement-annotated.");

    BeanWrapperImpl src = new BeanWrapperImpl(object);

    xew.writeStartElement(e.name());//from  w  ww  . j  a va 2  s.co m

    if (id != null)
        xew.writeAttribute("id", id);

    HashSet<String> attributes = new HashSet<String>();
    for (Method m : clazz.getMethods()) {
        if (!m.getName().startsWith("set"))
            continue;
        String propertyName = AnnotUtils.dejavaify(m.getName().substring(3));
        MCAttribute a = m.getAnnotation(MCAttribute.class);
        if (a != null) {
            Object value = src.getPropertyValue(propertyName);
            String str;
            if (value == null)
                continue;
            else if (value instanceof String)
                str = (String) value;
            else if (value instanceof Boolean)
                str = ((Boolean) value).toString();
            else if (value instanceof Integer)
                str = ((Integer) value).toString();
            else if (value instanceof Long)
                str = ((Long) value).toString();
            else if (value instanceof Enum<?>)
                str = value.toString();
            else {
                MCElement el = value.getClass().getAnnotation(MCElement.class);
                if (el != null) {
                    str = defineBean(sc, value, null, true);
                } else {
                    str = "?";
                    sc.incomplete = true;
                }
            }

            if (a.attributeName().length() > 0)
                propertyName = a.attributeName();

            attributes.add(propertyName);
            xew.writeAttribute(propertyName, str);
        }
    }
    for (Method m : clazz.getMethods()) {
        if (!m.getName().startsWith("set"))
            continue;
        String propertyName = AnnotUtils.dejavaify(m.getName().substring(3));
        MCOtherAttributes o = m.getAnnotation(MCOtherAttributes.class);
        if (o != null) {
            Object value = src.getPropertyValue(propertyName);
            if (value instanceof Map<?, ?>) {
                Map<?, ?> map = (Map<?, ?>) value;
                for (Map.Entry<?, ?> entry : map.entrySet()) {
                    Object key = entry.getKey();
                    Object val = entry.getValue();
                    if (!(key instanceof String) || !(val instanceof String)) {
                        sc.incomplete = true;
                        key = "incompleteAttributes";
                        val = "?";
                    }
                    if (attributes.contains(key))
                        continue;
                    attributes.add((String) key);
                    xew.writeAttribute((String) key, (String) val);
                }
            } else {
                xew.writeAttribute("incompleteAttributes", "?");
                sc.incomplete = true;
            }
        }
    }

    List<Method> childElements = new ArrayList<Method>();
    for (Method m : clazz.getMethods()) {
        if (!m.getName().startsWith("set"))
            continue;
        String propertyName = AnnotUtils.dejavaify(m.getName().substring(3));

        MCChildElement c = m.getAnnotation(MCChildElement.class);
        if (c != null) {
            childElements.add(m);
        }
        MCTextContent t = m.getAnnotation(MCTextContent.class);
        if (t != null) {
            Object value = src.getPropertyValue(propertyName);
            if (value == null) {
                continue;
            } else if (value instanceof String) {
                xew.writeCharacters((String) value);
            } else {
                xew.writeCharacters("?");
                sc.incomplete = true;
            }
        }
    }

    Collections.sort(childElements, new Comparator<Method>() {

        @Override
        public int compare(Method o1, Method o2) {
            MCChildElement c1 = o1.getAnnotation(MCChildElement.class);
            MCChildElement c2 = o2.getAnnotation(MCChildElement.class);
            return c1.order() - c2.order();
        }
    });

    for (Method m : childElements) {
        String propertyName = AnnotUtils.dejavaify(m.getName().substring(3));

        Object value = src.getPropertyValue(propertyName);
        if (value != null) {
            if (value instanceof Collection<?>) {
                for (Object item : (Collection<?>) value)
                    addXML(item, null, xew, sc);
            } else {
                addXML(value, null, xew, sc);
            }
        }
    }

    xew.writeEndElement();
}

From source file:framework.GlobalHelpers.java

public static Action findAction(String className, String action) {
    if (Config.isInProductionMode()) {
        return findActionOnProduction(className, action);
    } else {//from www. java2 s .  co m
        try {
            Class<?> clazz = Thread.currentThread().getContextClassLoader().loadClass(className);
            Method[] methods = clazz.getMethods();
            Method actionMethod = null;
            for (Method method : methods) {
                if (method.getName().equals(action)) {
                    actionMethod = method;
                }
            }
            if (actionMethod != null) {
                Action instance = new Action(action, getControllerInstance(clazz), actionMethod);
                return instance;
            } else {
                return null;
            }
        } catch (ClassNotFoundException e) {
            return null;
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }
}

From source file:it.unibo.alchemist.language.protelis.util.ProtelisLoader.java

private static MethodCall parseMethod(final JvmOperation jvmOp, final List<Expression> args,
        final Map<FasterString, FunctionDefinition> nameToFun,
        final Map<FunctionDef, FunctionDefinition> funToFun, final AtomicInteger id) {
    final boolean ztatic = jvmOp.isStatic();
    final List<AnnotatedTree<?>> arguments = parseArgs(args, nameToFun, funToFun, id);
    final String classname = jvmOp.getDeclaringType().getQualifiedName();
    try {//from  w w w.  j a  v a 2s  . c o m
        final Class<?> clazz = Class.forName(classname);
        /*
         * TODO: Check for return type and params: if param is Field and
         * return type is not then L.warn()
         */
        List<Method> tempList = new ArrayList<>();
        for (Method m : clazz.getMethods()) {
            if (ztatic) {
                if (Modifier.isStatic(m.getModifiers())) {
                    tempList.add(m);
                }
            }
        }
        /*
         * Same number of arguments
         */
        final int parameterCount = jvmOp.getParameters().size();
        List<Method> tempList2 = new ArrayList<>();
        for (Method m : tempList) {
            // TODO: Workaround for different Method API
            if (m.getParameterTypes().length == parameterCount) {
                tempList2.add(m);
            }
        }
        /*
         * Same name
         */
        final String methodName = jvmOp.getSimpleName();
        List<Method> res = new ArrayList<>();
        for (Method m : tempList2) {
            if (m.getName().equals(methodName)) {
                res.add(m);
            }
        }
        /*
         * There should be only one left - otherwise we have overloading,
         * and to properly deal with that we need type checking. The
         * following collection operation is for debug and warning purposes,
         * and should be removed as soon as we have a proper way to deal
         * with overloading in place. TODO
         */
        if (res.size() > 1) {
            final StringBuilder sb = new StringBuilder(64);
            sb.append("Method ");
            sb.append(jvmOp.getQualifiedName());
            sb.append('/');
            sb.append(parameterCount);
            sb.append(" is overloaded by:\n");
            for (Method m : res) {
                sb.append(m.toString());
                sb.append('\n'); // NOPMD
            }
            sb.append("Protelis can not (yet) properly deal with that.");
            L.warn(sb.toString());
        }
        if (res.isEmpty()) {
            throw new IllegalStateException("Can not bind any method that satisfies the name "
                    + jvmOp.getQualifiedName() + "/" + parameterCount + ".");
        }
        return new MethodCall(res.get(0), arguments, ztatic);
    } catch (ClassNotFoundException e) {
        throw new IllegalStateException("Class " + classname + " could not be found in classpath.");
    } catch (SecurityException e) {
        throw new IllegalStateException(
                "Class " + classname + " could not be loaded due to security permissions.");
    } catch (Error e) {
        throw new IllegalStateException("An error occured while loading class " + classname + ".");
    }

}

From source file:lucee.transformer.bytecode.reflection.ASMProxyFactory.java

public static ASMClass getClass(ExtendableClassLoader pcl, Resource classRoot, Class clazz)
        throws IOException, InstantiationException, IllegalAccessException, IllegalArgumentException,
        SecurityException, InvocationTargetException, NoSuchMethodException {
    Type type = Type.getType(clazz);

    // Fields//from www . ja  va 2s.c  o  m
    Field[] fields = clazz.getFields();
    for (int i = 0; i < fields.length; i++) {
        if (Modifier.isPrivate(fields[i].getModifiers()))
            continue;
        createField(type, fields[i]);
    }

    // Methods
    Method[] methods = clazz.getMethods();
    Map<String, ASMMethod> amethods = new HashMap<String, ASMMethod>();
    for (int i = 0; i < methods.length; i++) {
        if (Modifier.isPrivate(methods[i].getModifiers()))
            continue;
        amethods.put(methods[i].getName(), getMethod(pcl, classRoot, type, clazz, methods[i]));
    }

    return new ASMClass(clazz.getName(), amethods);

}

From source file:cn.aposoft.util.spring.ReflectionUtils.java

private static List<Method> findConcreteMethodsOnInterfaces(Class<?> clazz) {
    List<Method> result = null;
    for (Class<?> ifc : clazz.getInterfaces()) {
        for (Method ifcMethod : ifc.getMethods()) {
            if (!Modifier.isAbstract(ifcMethod.getModifiers())) {
                if (result == null) {
                    result = new LinkedList<Method>();
                }/*from  ww w  . j av a2  s  . c om*/
                result.add(ifcMethod);
            }
        }
    }
    return result;
}

From source file:io.fabric8.maven.core.util.KubernetesResourceUtil.java

/**
 * Uses reflection to copy over default values from the defaultValues object to the targetValues
 * object similar to the following:/*  ww w .j a va  2  s . c om*/
 *
 * <code>
\    * if( values.get${FIELD}() == null ) {
 *   values.(with|set){FIELD}(defaultValues.get${FIELD});
 * }
 * </code>
 *
 * Only fields that which use primitives, boxed primitives, or String object are copied.
 *
 * @param targetValues
 * @param defaultValues
 */
public static void mergeSimpleFields(Object targetValues, Object defaultValues) {
    Class<?> tc = targetValues.getClass();
    Class<?> sc = defaultValues.getClass();
    for (Method targetGetMethod : tc.getMethods()) {
        if (!targetGetMethod.getName().startsWith("get")) {
            continue;
        }

        Class<?> fieldType = targetGetMethod.getReturnType();
        if (!SIMPLE_FIELD_TYPES.contains(fieldType)) {
            continue;
        }

        String fieldName = targetGetMethod.getName().substring(3);
        Method withMethod = null;
        try {
            withMethod = tc.getMethod("with" + fieldName, fieldType);
        } catch (NoSuchMethodException e) {
            try {
                withMethod = tc.getMethod("set" + fieldName, fieldType);
            } catch (NoSuchMethodException e2) {
                continue;
            }
        }

        Method sourceGetMethod = null;
        try {
            sourceGetMethod = sc.getMethod("get" + fieldName);
        } catch (NoSuchMethodException e) {
            continue;
        }

        try {
            if (targetGetMethod.invoke(targetValues) == null) {
                withMethod.invoke(targetValues, sourceGetMethod.invoke(defaultValues));
            }
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e.getCause());
        }
    }
}

From source file:it.unibo.alchemist.language.protelis.util.ReflectionUtils.java

private static Method loadBestMethod(final Class<?> clazz, final String methodName, final Class<?>[] argClass) {
    Objects.requireNonNull(clazz, "The class on which the method will be invoked can not be null.");
    Objects.requireNonNull(methodName, "Method name can not be null.");
    Objects.requireNonNull(argClass, "Method arguments can not be null.");
    /*/*w  w w  .  java2s . c o  m*/
     * If there is a matching method, return it
     */
    try {
        return clazz.getMethod(methodName, argClass);
    } catch (NoSuchMethodException | SecurityException e) {
        /*
         * Look it up on the cache
         */
        /*
         * Deal with Java method overloading scoring methods
         */
        final Method[] candidates = clazz.getMethods();
        final List<Pair<Integer, Method>> lm = new ArrayList<>(candidates.length);
        for (final Method m : candidates) {
            // TODO: Workaround for different Method API
            if (m.getParameterTypes().length == argClass.length && methodName.equals(m.getName())) {
                final Class<?>[] params = m.getParameterTypes();
                int p = 0;
                boolean compatible = true;
                for (int i = 0; compatible && i < argClass.length; i++) {
                    final Class<?> expected = params[i];
                    if (expected.isAssignableFrom(argClass[i])) {
                        /*
                         * No downcast required, there is compatibility
                         */
                        p++;
                    } else if (!PrimitiveUtils.classIsNumber(expected)) {
                        compatible = false;
                    }
                }
                if (compatible) {
                    lm.add(new Pair<>(p, m));
                }
            }
        }
        /*
         * Find best
         */
        if (lm.size() > 0) {
            Pair<Integer, Method> max = lm.get(0);
            for (Pair<Integer, Method> cPair : lm) {
                if (cPair.getFirst().compareTo(max.getFirst()) > 0) {
                    max = cPair;
                }
            }
            return max.getSecond();
        }
    }
    List<Class<?>> list = new ArrayList<>();
    for (Class<?> c : argClass) {
        list.add(c);
    }
    final String argType = list.toString();
    throw new NoSuchMethodError(
            methodName + "/" + argClass.length + argType + " does not exist in " + clazz + ".");
}

From source file:gov.nih.nci.system.web.util.RESTUtil.java

public static void printObject(Object obj, Class klass, boolean includeAssociation) throws Exception {
    System.out.println("\nPrinting " + klass.getName());
    Method[] methods = klass.getMethods();
    for (Method method : methods) {
        if (method.getName().startsWith("get") && !method.getName().equals("getClass")) {
            System.out.print("\t" + method.getName().substring(3) + ":");
            Object val = null;
            try {
                val = method.invoke(obj, (Object[]) null);
            } catch (Exception e) {
                val = "ERROR - unable to determine value";

            }/* w ww.  j ava  2s  .c  o m*/
            if (val instanceof java.util.Set) {
                System.out.println("\n instanceof java.util.Set Printing Collection.....");
                Collection list = (Collection) val;
                for (Object object : list) {
                    System.out.println(object.getClass().getName() + ":");
                    if (includeAssociation) {
                        printObject(object, object.getClass(), false);
                    } else {
                        System.out.println(" -- association has been excluded");
                    }
                }
                log.debug("size=" + ((Collection) val).size());
            } else if (val instanceof ArrayList) {
                Collection list = (ArrayList) val;
                System.out.println("\n instanceof ArrayList Printing Collection.....");
                for (Object object : list) {
                    System.out.println(object.getClass().getName() + ":");
                    if (includeAssociation) {
                        printObject(object, object.getClass(), false);
                    } else {
                        System.out.println(" -- association has been excluded");
                    }
                }
            } else if (val != null && val.getClass().getName().startsWith("gov.nih.nci")) {
                if (includeAssociation) {
                    printObject(val, val.getClass(), false);
                } else {
                    System.out.println(" -- association has been excluded");
                }
            } else
                System.out.println(val);
        }
    }
}