Example usage for java.lang.reflect Method getName

List of usage examples for java.lang.reflect Method getName

Introduction

In this page you can find the example usage for java.lang.reflect Method getName.

Prototype

@Override
public String getName() 

Source Link

Document

Returns the name of the method represented by this Method object, as a String .

Usage

From source file:com.jetyun.pgcd.rpc.reflect.ClassAnalyzer.java

/**
 * Analyze a class and create a ClassData object containing all of the
 * public methods (both static and non-static) in the class.
 * //  w ww .  j a  v  a  2s.co m
 * @param clazz
 *            class to be analyzed.
 * 
 * @return a ClassData object containing all the public static and
 *         non-static methods that can be invoked on the class.
 */
private static ClassData analyzeClass(Class clazz) {
    log.info("analyzing " + clazz.getName());
    Method methods[] = clazz.getMethods();
    ClassData cd = new ClassData();
    cd.clazz = clazz;

    // Create temporary method map
    HashMap staticMethodMap = new HashMap();
    HashMap methodMap = new HashMap();
    for (int i = 0; i < methods.length; i++) {
        Method method = methods[i];
        if (method.getDeclaringClass() == Object.class) {
            continue;
        }
        int mod = methods[i].getModifiers();
        if (!Modifier.isPublic(mod)) {
            continue;
        }
        Class param[] = method.getParameterTypes();

        // don't count locally resolved args
        int argCount = 0;
        for (int n = 0; n < param.length; n++) {
            if (LocalArgController.isLocalArg(param[n])) {
                continue;
            }
            argCount++;
        }

        MethodKey mk = new MethodKey(method.getName(), argCount);
        ArrayList marr = (ArrayList) methodMap.get(mk);
        if (marr == null) {
            marr = new ArrayList();
            methodMap.put(mk, marr);
        }
        marr.add(method);
        if (Modifier.isStatic(mod)) {
            marr = (ArrayList) staticMethodMap.get(mk);
            if (marr == null) {
                marr = new ArrayList();
                staticMethodMap.put(mk, marr);
            }
            marr.add(method);
        }
    }
    cd.methodMap = new HashMap();
    cd.staticMethodMap = new HashMap();
    // Convert ArrayLists to arrays
    Iterator i = methodMap.entrySet().iterator();
    while (i.hasNext()) {
        Map.Entry entry = (Map.Entry) i.next();
        MethodKey mk = (MethodKey) entry.getKey();
        ArrayList marr = (ArrayList) entry.getValue();
        if (marr.size() == 1) {
            cd.methodMap.put(mk, marr.get(0));
        } else {
            cd.methodMap.put(mk, marr.toArray(new Method[0]));
        }
    }
    i = staticMethodMap.entrySet().iterator();
    while (i.hasNext()) {
        Map.Entry entry = (Map.Entry) i.next();
        MethodKey mk = (MethodKey) entry.getKey();
        ArrayList marr = (ArrayList) entry.getValue();
        if (marr.size() == 1) {
            cd.staticMethodMap.put(mk, marr.get(0));
        } else {
            cd.staticMethodMap.put(mk, marr.toArray(new Method[0]));
        }
    }
    return cd;
}

From source file:com.snaplogic.snaps.firstdata.Create.java

static boolean isSetter(Method method) {
    return Modifier.isPublic(method.getModifiers()) && method.getReturnType().equals(void.class)
            && method.getParameterTypes().length == 1 && method.getName().matches(REGEX_SET);
}

From source file:com.datatorrent.lib.util.PojoUtils.java

private static String getSingleFieldSetterExpression(final Class<?> pojoClass, final String fieldExpression,
        final Class<?> exprClass) {
    JavaStatement code = new JavaStatement(
            pojoClass.getName().length() + fieldExpression.length() + exprClass.getName().length() + 32);
    /* Construct ((<pojo class name>)pojo). */
    code.appendCastToTypeExpr(pojoClass, OBJECT).append(".");
    try {//  w  w  w  . ja  va  2  s.  c o  m
        final Field field = pojoClass.getField(fieldExpression);
        if (ClassUtils.isAssignable(exprClass, field.getType())) {
            /* there is public field on the class, use direct assignment. */
            /* append <field name> = (<field type>)val; */
            return code.append(field.getName()).append(" = ").appendCastToTypeExpr(exprClass, VAL)
                    .getStatement();
        }
        logger.debug("{} can not be assigned to {}. Proceeding to locate a setter method.", exprClass, field);
    } catch (NoSuchFieldException ex) {
        logger.debug("{} does not have field {}. Proceeding to locate a setter method.", pojoClass,
                fieldExpression);
    } catch (SecurityException ex) {
        logger.debug("{} does not have field {}. Proceeding to locate a setter method.", pojoClass,
                fieldExpression);
    }

    final String setMethodName = SET + upperCaseWord(fieldExpression);
    Method bestMatchMethod = null;
    List<Method> candidates = new ArrayList<Method>();
    for (Method method : pojoClass.getMethods()) {
        if (setMethodName.equals(method.getName())) {
            Class<?>[] parameterTypes = method.getParameterTypes();
            if (parameterTypes.length == 1) {
                if (exprClass == parameterTypes[0]) {
                    bestMatchMethod = method;
                    break;
                } else if (ClassUtils.isAssignable(exprClass, parameterTypes[0])) {
                    candidates.add(method);
                }
            }
        }
    }

    if (bestMatchMethod == null) { // We did not find the exact match, use candidates to find the match
        if (candidates.size() == 0) {
            logger.debug("{} does not have suitable setter method {}. Returning original expression {}.",
                    pojoClass, setMethodName, fieldExpression);
            /* We did not find any match at all, use original expression */
            /* append = (<expr type>)val;*/
            return code.append(fieldExpression).append(" = ").appendCastToTypeExpr(exprClass, VAL)
                    .getStatement();
        } else {
            // TODO: see if we can find a better match
            bestMatchMethod = candidates.get(0);
        }
    }

    /* We found a method that we may use for setter */
    /* append <method name>((<expr class)val); */
    return code.append(bestMatchMethod.getName()).append("(").appendCastToTypeExpr(exprClass, VAL).append(")")
            .getStatement();
}

From source file:com.linkedin.helix.TestHelper.java

private static Method getMethod(String name) {
    Method[] methods = TestHelper.class.getMethods();
    for (Method method : methods) {
        if (name.equals(method.getName())) {
            return method;
        }//from w  ww  .  j  av  a 2  s.c o m
    }
    return null;
}

From source file:org.mwc.debrief.editable.test.EditableTests.java

/**
* test helper, to check that all of the object property getters/setters are
* there//from  w w  w.  j a va  2  s . c  o m
* 
* @param toBeTested
*/
public static void testTheseParameters(final Editable toBeTested) {
    // check if we received an object
    System.out.println("testing " + toBeTested.getClass());
    if (toBeTested == null)
        return;

    Assert.assertNotNull("Found editable object", toBeTested);

    final Editable.EditorType et = toBeTested.getInfo();

    if (et == null) {
        Assert.fail("no editor type returned for");
        return;
    }

    // first see if we return a custom bean descriptor
    final BeanDescriptor desc = et.getBeanDescriptor();

    // did we get one?
    if (desc != null) {
        final Class<?> editorClass = desc.getCustomizerClass();
        if (editorClass != null) {
            Object newInstance = null;
            try {
                newInstance = editorClass.newInstance();
            } catch (final InstantiationException e) {
                e.printStackTrace(); // To change body of catch statement use File
                                     // | Settings | File Templates.
            } catch (final IllegalAccessException e) {
                e.printStackTrace(); // To change body of catch statement use File
                                     // | Settings | File Templates.
            }
            // check it worked
            Assert.assertNotNull("we didn't create the custom editor for:", newInstance);
        } else {
            // there isn't a dedicated editor, try the custom ones.
            // do the edits
            PropertyDescriptor[] pd = null;
            try {
                pd = et.getPropertyDescriptors();
            } catch (Exception e) {
                org.mwc.debrief.editable.test.Activator.log(e);
                Assert.fail("problem fetching property editors for " + toBeTested.getClass());
            }

            if (pd == null) {
                Assert.fail("problem fetching property editors for " + toBeTested.getClass());
                return;
            }

            final int len = pd.length;
            if (len == 0) {
                System.out.println(
                        "zero property editors found for " + toBeTested + ", " + toBeTested.getClass());
                return;
            }

            // griddable property descriptors
            if (et instanceof Griddable) {
                pd = null;
                try {
                    pd = ((Griddable) et).getGriddablePropertyDescriptors();
                } catch (Exception e) {
                    org.mwc.debrief.editable.test.Activator.log(e);
                    Assert.fail("problem fetching griddable property editors for " + toBeTested.getClass());
                }

                if (pd == null) {
                    Assert.fail("problem fetching griddable property editors for " + toBeTested.getClass());
                    return;
                }
            }
            // the method names are checked when creating PropertyDescriptor
            // we haven't to test them

        } // whether there was a customizer class
    } // whether there was a custom bean descriptor

    // now try out the methods
    final MethodDescriptor[] methods = et.getMethodDescriptors();
    if (methods != null) {
        for (int thisM = 0; thisM < methods.length; thisM++) {
            final MethodDescriptor method = methods[thisM];
            final Method thisOne = method.getMethod();
            final String theName = thisOne.getName();
            Assert.assertNotNull(theName);
        }
    }
}

From source file:com.helpinput.utils.Utils.java

public static Method findMethod(Class<?> targetClass, String methodName, Class<?>[] agrsClasses) {
    Method[] methods = targetClass.getDeclaredMethods();
    Method theMethod = null;/*from w  w  w .ja  v a 2s . c  o  m*/

    for (Method method : methods) {
        if (method.getName().equals(methodName)) {
            Class<?>[] classes = method.getParameterTypes();

            if (agrsClasses.length == 0 && classes.length == 0) {
                theMethod = method;
                break;
            }

            if (agrsClasses.length == classes.length) {
                for (int i = 0; i < agrsClasses.length; i++) {
                    if (agrsClasses[i] == null) {
                        if (i == agrsClasses.length - 1) {
                            theMethod = method;
                            break;
                        }
                        continue;
                    }
                    if (classes[i].isPrimitive()) {
                        if (!primitiveWrap(classes[i]).isAssignableFrom(agrsClasses[i]))
                            break;
                    } else if (!classes[i].isAssignableFrom(agrsClasses[i]))
                        break;
                    if (i == agrsClasses.length - 1) {
                        theMethod = method;
                        break;
                    }
                }
            }
            if (theMethod != null)
                break;
        }
        if (theMethod != null)
            break;
    }

    if (null != theMethod) {
        return accessible(theMethod);
    } else {
        if (targetClass.getSuperclass() != null) {
            return findMethod(targetClass.getSuperclass(), methodName, agrsClasses);
        }
        return null;
    }
}

From source file:com.ikanow.aleph2.data_model.utils.CrudServiceUtils.java

/** CRUD service proxy that optionally adds an extra term and allows the user to modify the results after they've run (eg to apply security service settings) 
 * @author Alex/*from www . j a v  a  2  s. c om*/
 */
@SuppressWarnings("unchecked")
public static <T> ICrudService<T> intercept(final Class<T> clazz, final ICrudService<T> delegate,
        final Optional<QueryComponent<T>> extra_query,
        final Optional<Function<QueryComponent<T>, QueryComponent<T>>> query_transform,
        final Map<String, BiFunction<Object, Object[], Object>> interceptors,
        final Optional<BiFunction<Object, Object[], Object>> default_interceptor) {
    InvocationHandler handler = new InvocationHandler() {
        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            final Method m = delegate.getClass().getMethod(method.getName(), method.getParameterTypes());

            // First off, apply the extra term to any relevant args:
            final Object[] args_with_extra_query_pretransform = query_transform.map(q -> {
                return (null != args) ? Arrays.stream(args)
                        .map(o -> (null != o) && QueryComponent.class.isAssignableFrom(o.getClass())
                                ? q.apply((QueryComponent<T>) o)
                                : o)
                        .collect(Collectors.toList()).toArray() : args;
            }).orElse(args);

            final Object[] args_with_extra_query = extra_query.map(q -> {
                return (null != args_with_extra_query_pretransform)
                        ? Arrays.stream(args_with_extra_query_pretransform)
                                .map(o -> (null != o) && QueryComponent.class.isAssignableFrom(o.getClass())
                                        ? CrudUtils.allOf((QueryComponent<T>) o, q)
                                        : o)
                                .collect(Collectors.toList()).toArray()
                        : args_with_extra_query_pretransform;
            }).orElse(args_with_extra_query_pretransform);

            // Special cases for: readOnlyVersion, getFilterdRepo / countObjects / getRawService / *byId
            final Object o = Lambdas.get(() -> {
                final SingleQueryComponent<T> base_query = JsonNode.class.equals(clazz)
                        ? (SingleQueryComponent<T>) CrudUtils.allOf()
                        : CrudUtils.allOf(clazz);

                try {
                    if (extra_query.isPresent() && m.getName().equals("countObjects")) { // special case....change method and apply spec
                        return delegate.countObjectsBySpec(extra_query.get());
                    } else if (extra_query.isPresent() && m.getName().equals("getObjectById")) { // convert from id to spec and append extra_query
                        if (1 == args.length) {
                            return delegate.getObjectBySpec(CrudUtils.allOf(extra_query.get(),
                                    base_query.when(JsonUtils._ID, args[0])));
                        } else {
                            return delegate.getObjectBySpec(
                                    CrudUtils.allOf(extra_query.get(), base_query.when(JsonUtils._ID, args[0])),
                                    (List<String>) args[1], (Boolean) args[2]);
                        }
                    } else if (extra_query.isPresent() && m.getName().equals("deleteDatastore")) {
                        CompletableFuture<Long> l = delegate.deleteObjectsBySpec(extra_query.get());
                        return l.thenApply(ll -> ll > 0);
                    } else if (extra_query.isPresent() && m.getName().equals("deleteObjectById")) { // convert from id to spec and append extra_query
                        return delegate.deleteObjectBySpec(
                                CrudUtils.allOf(extra_query.get(), base_query.when(JsonUtils._ID, args[0])));
                    } else if (extra_query.isPresent() && m.getName().equals("updateObjectById")) { // convert from id to spec and append extra_query
                        return delegate.updateObjectBySpec(
                                CrudUtils.allOf(extra_query.get(), base_query.when(JsonUtils._ID, args[0])),
                                Optional.empty(), (UpdateComponent<T>) args[1]);
                    } else if (m.getName().equals("getRawService")) { // special case....convert the default query to JSON, if present
                        Object o_internal = m.invoke(delegate, args_with_extra_query);
                        Optional<QueryComponent<JsonNode>> json_extra_query = extra_query
                                .map(qc -> qc.toJson());
                        return intercept(JsonNode.class, (ICrudService<JsonNode>) o_internal, json_extra_query,
                                Optional.empty(), interceptors, default_interceptor);
                    } else { // wrap any CrudService types
                        Object o_internal = m.invoke(delegate, args_with_extra_query);
                        return (null != o_internal)
                                && ICrudService.class.isAssignableFrom(o_internal.getClass())
                                        ? intercept(clazz, (ICrudService<T>) o_internal, extra_query,
                                                Optional.empty(), interceptors, default_interceptor)
                                        : o_internal;
                    }
                } catch (IllegalAccessException ee) {
                    throw new RuntimeException(ee);
                } catch (InvocationTargetException e) {
                    throw new RuntimeException(e.getCause().getMessage(), e);
                }
            });

            return interceptors
                    .getOrDefault(m.getName(),
                            default_interceptor.orElse(CrudServiceUtils::identityInterceptor))
                    .apply(o, args_with_extra_query);
        }
    };

    return ICrudService.IReadOnlyCrudService.class.isAssignableFrom(delegate.getClass())
            ? (ICrudService<T>) Proxy.newProxyInstance(ICrudService.IReadOnlyCrudService.class.getClassLoader(),
                    new Class[] { ICrudService.IReadOnlyCrudService.class }, handler)
            : (ICrudService<T>) Proxy.newProxyInstance(ICrudService.class.getClassLoader(),
                    new Class[] { ICrudService.class }, handler);
}

From source file:framework.GlobalHelpers.java

public static Action findAction(String className, String action) {
    if (Config.isInProductionMode()) {
        return findActionOnProduction(className, action);
    } else {/*from  ww  w. j  a v  a  2  s. c o 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:com.gargoylesoftware.htmlunit.javascript.configuration.AbstractJavaScriptConfiguration.java

private static void process(final ClassConfiguration classConfiguration, final String hostClassName,
        final String expectedBrowserName, final float browserVersionNumeric) {
    final String simpleClassName = hostClassName.substring(hostClassName.lastIndexOf('.') + 1);

    CLASS_NAME_MAP_.put(hostClassName, simpleClassName);
    final Map<String, Method> allGetters = new HashMap<>();
    final Map<String, Method> allSetters = new HashMap<>();
    for (final Constructor<?> constructor : classConfiguration.getHostClass().getDeclaredConstructors()) {
        for (final Annotation annotation : constructor.getAnnotations()) {
            if (annotation instanceof JsxConstructor) {
                if (isSupported(((JsxConstructor) annotation).value(), expectedBrowserName,
                        browserVersionNumeric)) {
                    classConfiguration.setJSConstructor(constructor);
                }//from  www  . ja  v  a 2s .  c  o m
            }
        }
    }
    for (final Method method : classConfiguration.getHostClass().getDeclaredMethods()) {
        for (final Annotation annotation : method.getAnnotations()) {
            if (annotation instanceof JsxGetter) {
                final JsxGetter jsxGetter = (JsxGetter) annotation;
                if (isSupported(jsxGetter.value(), expectedBrowserName, browserVersionNumeric)) {
                    String property;
                    if (jsxGetter.propertyName().isEmpty()) {
                        final int prefix = method.getName().startsWith("is") ? 2 : 3;
                        property = method.getName().substring(prefix);
                        property = Character.toLowerCase(property.charAt(0)) + property.substring(1);
                    } else {
                        property = jsxGetter.propertyName();
                    }
                    allGetters.put(property, method);
                }
            } else if (annotation instanceof JsxSetter) {
                final JsxSetter jsxSetter = (JsxSetter) annotation;
                if (isSupported(jsxSetter.value(), expectedBrowserName, browserVersionNumeric)) {
                    String property;
                    if (jsxSetter.propertyName().isEmpty()) {
                        property = method.getName().substring(3);
                        property = Character.toLowerCase(property.charAt(0)) + property.substring(1);
                    } else {
                        property = jsxSetter.propertyName();
                    }
                    allSetters.put(property, method);
                }
            } else if (annotation instanceof JsxFunction) {
                if (isSupported(((JsxFunction) annotation).value(), expectedBrowserName,
                        browserVersionNumeric)) {
                    classConfiguration.addFunction(method);
                }
            } else if (annotation instanceof JsxStaticGetter) {
                final JsxStaticGetter jsxStaticGetter = (JsxStaticGetter) annotation;
                if (isSupported(jsxStaticGetter.value(), expectedBrowserName, browserVersionNumeric)) {
                    final int prefix = method.getName().startsWith("is") ? 2 : 3;
                    String property = method.getName().substring(prefix);
                    property = Character.toLowerCase(property.charAt(0)) + property.substring(1);
                    classConfiguration.addStaticProperty(property, method, null);
                }
            } else if (annotation instanceof JsxStaticFunction) {
                if (isSupported(((JsxStaticFunction) annotation).value(), expectedBrowserName,
                        browserVersionNumeric)) {
                    classConfiguration.addStaticFunction(method);
                }
            } else if (annotation instanceof JsxConstructor) {
                if (isSupported(((JsxConstructor) annotation).value(), expectedBrowserName,
                        browserVersionNumeric)) {
                    classConfiguration.setJSConstructor(method);
                }
            }
        }
    }
    for (final Field field : classConfiguration.getHostClass().getDeclaredFields()) {
        final JsxConstant jsxConstant = field.getAnnotation(JsxConstant.class);
        if (jsxConstant != null
                && isSupported(jsxConstant.value(), expectedBrowserName, browserVersionNumeric)) {
            classConfiguration.addConstant(field.getName());
        }
    }
    for (final Entry<String, Method> getterEntry : allGetters.entrySet()) {
        final String property = getterEntry.getKey();
        classConfiguration.addProperty(property, getterEntry.getValue(), allSetters.get(property));
    }
}