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.predic8.membrane.annot.bean.MCUtil.java

@SuppressWarnings("unchecked")
public static <T> T clone(T object, boolean deep) {
    try {//  w w  w . j ava  2s . c  o  m
        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 dst = new BeanWrapperImpl(clazz);
        BeanWrapperImpl src = new BeanWrapperImpl(object);

        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) {
                dst.setPropertyValue(propertyName, src.getPropertyValue(propertyName));
            }
            MCChildElement c = m.getAnnotation(MCChildElement.class);
            if (c != null) {
                if (deep) {
                    dst.setPropertyValue(propertyName, cloneInternal(src.getPropertyValue(propertyName), deep));
                } else {
                    dst.setPropertyValue(propertyName, src.getPropertyValue(propertyName));
                }
            }
            MCOtherAttributes o = m.getAnnotation(MCOtherAttributes.class);
            if (o != null) {
                dst.setPropertyValue(propertyName, src.getPropertyValue(propertyName));
            }
            MCTextContent t = m.getAnnotation(MCTextContent.class);
            if (t != null) {
                dst.setPropertyValue(propertyName, src.getPropertyValue(propertyName));
            }
        }

        return (T) dst.getRootInstance();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.springframework.beans.BeanUtils.java

/**
 * Find a method with the given method name and minimal parameters (best case: none)
 * in the given list of methods.//  w w  w. j  ava 2 s.co m
 * @param methods the methods to check
 * @param methodName the name of the method to find
 * @return the Method object, or {@code null} if not found
 * @throws IllegalArgumentException if methods of the given name were found but
 * could not be resolved to a unique method with minimal parameters
 */
public static Method findMethodWithMinimalParameters(Method[] methods, String methodName)
        throws IllegalArgumentException {

    Method targetMethod = null;
    int numMethodsFoundWithCurrentMinimumArgs = 0;
    for (Method method : methods) {
        if (method.getName().equals(methodName)) {
            int numParams = method.getParameterTypes().length;
            if (targetMethod == null || numParams < targetMethod.getParameterTypes().length) {
                targetMethod = method;
                numMethodsFoundWithCurrentMinimumArgs = 1;
            } else {
                if (targetMethod.getParameterTypes().length == numParams) {
                    // Additional candidate with same length
                    numMethodsFoundWithCurrentMinimumArgs++;
                }
            }
        }
    }
    if (numMethodsFoundWithCurrentMinimumArgs > 1) {
        throw new IllegalArgumentException("Cannot resolve method '" + methodName
                + "' to a unique method. Attempted to resolve to overloaded method with "
                + "the least number of parameters, but there were " + numMethodsFoundWithCurrentMinimumArgs
                + " candidates.");
    }
    return targetMethod;
}

From source file:sh.scrap.scrapper.functions.StringFunctionFactory.java

private static String key(Method method) {
    String[] names = discoverer.getParameterNames(method);
    if (names == null)
        names = new String[0];
    List<String> args = new ArrayList<>(Arrays.asList(names));
    if (args.size() >= 2)
        args.set(1, "main");
    Collections.sort(args);/*  w  w  w . j a  v  a2  s. c om*/
    return method.getName() + ":" + args;
}

From source file:com.earnstone.geo.GeocandraService.java

private static void loadCassandraSettings(CassandraHostConfigurator config, String settings) {
    try {//from  w  w w.java 2 s .c o m
        String[] keyvalues = settings.split(";");

        for (String keyValueStr : keyvalues) {
            String[] keyValue = keyValueStr.split("=");

            Method method = null;
            for (Method temp : config.getClass().getMethods()) {
                if (temp.getName().equals("set" + keyValue[0])) {
                    method = temp;
                    break;
                }
            }

            Object value = null;

            if (method.getParameterTypes()[0].getName().equals("int"))
                value = Integer.parseInt(keyValue[1]);
            else if (method.getParameterTypes()[0].getName().equals("long"))
                value = Integer.parseInt(keyValue[1]);
            else if (method.getParameterTypes()[0].getName().equals("boolean"))
                value = Boolean.parseBoolean(keyValue[1]);

            method.invoke(config, new Object[] { value });
        }
    } catch (Exception ex) {
        throw new IllegalArgumentException("Error with loading cassandra settings", ex);
    }
}

From source file:IntrospectionUtil.java

public static boolean isSameSignature(Method methodA, Method methodB) {
    if (methodA == null)
        return false;
    if (methodB == null)
        return false;

    List parameterTypesA = Arrays.asList(methodA.getParameterTypes());
    List parameterTypesB = Arrays.asList(methodB.getParameterTypes());

    if (methodA.getName().equals(methodB.getName()) && parameterTypesA.containsAll(parameterTypesB))
        return true;

    return false;
}

From source file:com.amalto.core.metadata.ClassRepository.java

private static Method[] getMethods(Class clazz) {
    // TMDM-5851: Work around several issues in introspection (getDeclaredMethods() and getMethods() may return
    // inherited methods if returned type is a sub class of super class method).
    Map<String, Class<?>> superClassMethods = new HashMap<String, Class<?>>();
    if (clazz.getSuperclass() != null) {
        for (Method method : clazz.getSuperclass().getMethods()) {
            superClassMethods.put(method.getName(), method.getReturnType());
        }//from  ww  w .j a  v  a2  s  . c om
    }
    Map<String, Method> methods = new HashMap<String, Method>();
    for (Method method : clazz.getDeclaredMethods()) {
        if (!(superClassMethods.containsKey(method.getName())
                && superClassMethods.get(method.getName()).equals(method.getReturnType()))) {
            methods.put(method.getName(), method);
        }
    }
    Method[] allMethods = clazz.getMethods();
    for (Method method : allMethods) {
        if (!methods.containsKey(method.getName())) {
            methods.put(method.getName(), method);
        }
    }
    Method[] classMethods = methods.values().toArray(new Method[methods.size()]);
    // TMDM-5483: getMethods() does not always return methods in same order: sort them to ensure fixed order.
    Arrays.sort(classMethods, new Comparator<Method>() {
        @Override
        public int compare(Method method1, Method method2) {
            return method1.getName().compareTo(method2.getName());
        }
    });
    return classMethods;
}

From source file:com.weibo.api.motan.config.springsupport.MotanBeanDefinitionParser.java

@SuppressWarnings({ "rawtypes", "unchecked" })
private static BeanDefinition parse(Element element, ParserContext parserContext, Class<?> beanClass,
        boolean required) throws ClassNotFoundException {
    RootBeanDefinition bd = new RootBeanDefinition();
    bd.setBeanClass(beanClass);//from   w  w w .j  a  va 2  s  . co m
    // ??lazy init
    bd.setLazyInit(false);

    // id?id,idcontext
    String id = element.getAttribute("id");
    if ((id == null || id.length() == 0) && required) {
        String generatedBeanName = element.getAttribute("name");
        if (generatedBeanName == null || generatedBeanName.length() == 0) {
            generatedBeanName = element.getAttribute("class");
        }
        if (generatedBeanName == null || generatedBeanName.length() == 0) {
            generatedBeanName = beanClass.getName();
        }
        id = generatedBeanName;
        int counter = 2;
        while (parserContext.getRegistry().containsBeanDefinition(id)) {
            id = generatedBeanName + (counter++);
        }
    }
    if (id != null && id.length() > 0) {
        if (parserContext.getRegistry().containsBeanDefinition(id)) {
            throw new IllegalStateException("Duplicate spring bean id " + id);
        }
        parserContext.getRegistry().registerBeanDefinition(id, bd);
    }
    bd.getPropertyValues().addPropertyValue("id", id);
    if (ProtocolConfig.class.equals(beanClass)) {
        MotanNamespaceHandler.protocolDefineNames.add(id);

    } else if (RegistryConfig.class.equals(beanClass)) {
        MotanNamespaceHandler.registryDefineNames.add(id);

    } else if (BasicServiceInterfaceConfig.class.equals(beanClass)) {
        MotanNamespaceHandler.basicServiceConfigDefineNames.add(id);

    } else if (BasicRefererInterfaceConfig.class.equals(beanClass)) {
        MotanNamespaceHandler.basicRefererConfigDefineNames.add(id);

    } else if (ServiceConfigBean.class.equals(beanClass)) {
        String className = element.getAttribute("class");
        if (className != null && className.length() > 0) {
            RootBeanDefinition classDefinition = new RootBeanDefinition();
            classDefinition.setBeanClass(
                    Class.forName(className, true, Thread.currentThread().getContextClassLoader()));
            classDefinition.setLazyInit(false);
            parseProperties(element.getChildNodes(), classDefinition);
            bd.getPropertyValues().addPropertyValue("ref",
                    new BeanDefinitionHolder(classDefinition, id + "Impl"));
        }
    }

    Set<String> props = new HashSet<String>();
    ManagedMap parameters = null;
    // ??setbd
    for (Method setter : beanClass.getMethods()) {
        String name = setter.getName();
        // setXXX
        if (name.length() <= 3 || !name.startsWith("set") || !Modifier.isPublic(setter.getModifiers())
                || setter.getParameterTypes().length != 1) {
            continue;
        }
        String property = (name.substring(3, 4).toLowerCase() + name.substring(4)).replaceAll("_", "-");
        props.add(property);
        if ("id".equals(property)) {
            bd.getPropertyValues().addPropertyValue("id", id);
            continue;
        }
        String value = element.getAttribute(property);
        if ("methods".equals(property)) {
            parseMethods(id, element.getChildNodes(), bd, parserContext);
        }
        if (StringUtils.isBlank(value)) {
            continue;
        }
        value = value.trim();
        if (value.length() == 0) {
            continue;
        }
        Object reference;
        if ("ref".equals(property)) {
            if (parserContext.getRegistry().containsBeanDefinition(value)) {
                BeanDefinition refBean = parserContext.getRegistry().getBeanDefinition(value);
                if (!refBean.isSingleton()) {
                    throw new IllegalStateException(
                            "The exported service ref " + value + " must be singleton! Please set the " + value
                                    + " bean scope to singleton, eg: <bean id=\"" + value
                                    + "\" scope=\"singleton\" ...>");
                }
            }
            reference = new RuntimeBeanReference(value);
        } else if ("protocol".equals(property) && !StringUtils.isBlank(value)) {
            if (!value.contains(",")) {
                reference = new RuntimeBeanReference(value);
            } else {
                parseMultiRef("protocols", value, bd, parserContext);
                reference = null;
            }
        } else if ("registry".equals(property)) {
            parseMultiRef("registries", value, bd, parserContext);
            reference = null;
        } else if ("basicService".equals(property)) {
            reference = new RuntimeBeanReference(value);

        } else if ("basicReferer".equals(property)) {
            reference = new RuntimeBeanReference(value);

        } else if ("extConfig".equals(property)) {
            reference = new RuntimeBeanReference(value);
        } else {
            reference = new TypedStringValue(value);
        }

        if (reference != null) {
            bd.getPropertyValues().addPropertyValue(property, reference);
        }
    }
    if (ProtocolConfig.class.equals(beanClass)) {
        // protocolparameters?
        NamedNodeMap attributes = element.getAttributes();
        int len = attributes.getLength();
        for (int i = 0; i < len; i++) {
            Node node = attributes.item(i);
            String name = node.getLocalName();
            if (!props.contains(name)) {
                if (parameters == null) {
                    parameters = new ManagedMap();
                }
                String value = node.getNodeValue();
                parameters.put(name, new TypedStringValue(value, String.class));
            }
        }
        bd.getPropertyValues().addPropertyValue("parameters", parameters);
    }
    return bd;
}

From source file:net.radai.beanz.util.ReflectionUtil.java

public static String propNameFrom(Method method) {
    String methodName = method.getName();
    if (methodName.startsWith("get") || methodName.startsWith("set")) {
        if (methodName.length() > 4) {
            return methodName.substring(3, 4).toLowerCase(Locale.ROOT) + methodName.substring(4);
        } else {/*from www.ja  v  a2  s. c o m*/
            return methodName.substring(3, 4).toLowerCase(Locale.ROOT);
        }
    }
    if (methodName.startsWith("is")) {
        if (methodName.length() > 3) {
            return methodName.substring(2, 3).toLowerCase(Locale.ROOT) + methodName.substring(3);
        } else {
            return methodName.substring(2, 3).toLowerCase(Locale.ROOT);
        }
    }
    throw new IllegalArgumentException("method name " + methodName + " does not contain a property name");
}

From source file:com.revolsys.record.io.format.xml.XmlProcessor.java

/**
 * Create the cache of process methods from the specified class.
 *
 * @param processorClass The XmlPorcessor class.
 * @return The map of method names to process methods.
 *//* w ww . j  av  a 2  s  .c om*/
private static Map<String, Method> getMethodCache(final Class<?> processorClass) {
    Map<String, Method> methodCache = PROCESSOR_METHOD_CACHE.get(processorClass);
    if (methodCache == null) {
        methodCache = new HashMap<>();
        PROCESSOR_METHOD_CACHE.put(processorClass, methodCache);
        final Method[] methods = processorClass.getMethods();
        for (final Method method : methods) {
            final String methodName = method.getName();
            if (methodName.startsWith("process")) {
                if (Arrays.equals(method.getParameterTypes(), PROCESS_METHOD_ARGS)) {
                    final String name = methodName.substring(7);
                    methodCache.put(name, method);
                }
            }
        }
    }
    return methodCache;
}

From source file:com.github.itoshige.testrail.store.SyncManager.java

/**
 * add new test method in testrail and caseStore.
 * //from w  w w  .  j  a v  a2s.  com
 * @param sectionId
 * @param testClass
 */
private static void addNewTestMethod(String sectionId, final Class<?> testClass) {
    for (final Method method : TestRailUnitUtil.getDeclaredTestMethods(testClass.getDeclaredMethods())) {
        String caseId = "";
        try {
            caseId = CaseStore.getIns().getCaseId(new CaseStoreKey(sectionId, method.getName()));
        } catch (TestRailUnitException e) {
        }

        if (needToAddTestMethod(caseId, method)) {
            String title = method.getName();
            JSONObject createdCase = TestRailClient.addCase(sectionId, new CaseModel(title));
            CaseStore.getIns().add(createdCase, sectionId, title);
        }
    }
}