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:se.crisp.codekvast.agent.daemon.codebase.CodeBaseScanner.java

void findTrackedMethods(CodeBase codeBase, Set<String> packages, Set<String> excludePackages, Class<?> clazz) {
    if (clazz.isInterface()) {
        log.debug("Ignoring interface {}", clazz);
        return;/*from  w  w w  .  j ava  2  s. c  om*/
    }

    log.debug("Analyzing {}", clazz);
    MethodAnalyzer methodAnalyzer = codeBase.getConfig().getMethodAnalyzer();
    try {
        Method[] declaredMethods = clazz.getDeclaredMethods();
        Method[] methods = clazz.getMethods();
        Method[] allMethods = new Method[declaredMethods.length + methods.length];
        System.arraycopy(declaredMethods, 0, allMethods, 0, declaredMethods.length);
        System.arraycopy(methods, 0, allMethods, declaredMethods.length, methods.length);

        for (Method method : allMethods) {
            SignatureStatus status = methodAnalyzer.apply(method);

            // Some AOP frameworks (e.g., Guice) push methods from a base class down to subclasses created in runtime.
            // We need to map those back to the original declaring signature, or else the original declared method will look unused.

            MethodSignature thisSignature = SignatureUtils.makeMethodSignature(clazz, method);

            MethodSignature declaringSignature = SignatureUtils.makeMethodSignature(
                    findDeclaringClass(method.getDeclaringClass(), method, packages), method);

            if (shouldExcludeSignature(declaringSignature, excludePackages)) {
                status = SignatureStatus.EXCLUDED_BY_PACKAGE_NAME;
            }
            codeBase.addSignature(thisSignature, declaringSignature, status);
        }

        for (Class<?> innerClass : clazz.getDeclaredClasses()) {
            findTrackedMethods(codeBase, packages, excludePackages, innerClass);
        }
    } catch (NoClassDefFoundError e) {
        log.warn("Cannot analyze {}: {}", clazz, e.toString());
    }
}

From source file:com.datastax.hectorjpa.spring.ConsistencyLevelAspect.java

/**
 * Get the closest match to our method. Will check inheritance as well as
 * overloading/*from   w w w . ja v  a2 s .  co m*/
 * 
 * @param target
 * @param methodName
 * @param paramTypes
 * @return
 */
private Method getMatchingAccessibleMethod(Class<?> clazz, String methodName, Class<?>[] parameterTypes) {

    // search through all methods
    int paramSize = parameterTypes.length;
    Method bestMatch = null;
    Method[] methods = clazz.getMethods();
    float bestMatchCost = Float.MAX_VALUE;
    float myCost = Float.MAX_VALUE;
    for (int i = 0, size = methods.length; i < size; i++) {
        if (methods[i].getName().equals(methodName)) {

            // compare parameters
            Class<?>[] methodsParams = methods[i].getParameterTypes();
            int methodParamSize = methodsParams.length;
            if (methodParamSize == paramSize) {
                boolean match = true;
                for (int n = 0; n < methodParamSize; n++) {

                    if (!MethodUtils.isAssignmentCompatible(methodsParams[n], parameterTypes[n])) {

                        match = false;
                        break;
                    }
                }

                if (match) {
                    // get accessible version of method
                    Method method = MethodUtils.getAccessibleMethod(clazz, methods[i]);
                    if (method != null) {

                        myCost = getTotalTransformationCost(parameterTypes, method.getParameterTypes());
                        if (myCost < bestMatchCost) {
                            bestMatch = method;
                            bestMatchCost = myCost;
                        }
                    }

                }
            }
        }
    }

    return bestMatch;
}

From source file:net.jforum.core.support.hibernate.CacheEvictionRulesTestCase.java

private void executeTargetMethod(Class<?> entityClass, String methodName, Object... args) throws Exception {
    Object entity = this.getBean(entityClass.getName());

    Set<Method> methods = new HashSet<Method>(Arrays.asList(entityClass.getMethods()));
    methods.addAll(Arrays.asList(entityClass.getDeclaredMethods()));

    for (Method method : methods) {
        if (method.getName().equals(methodName)) {
            if (args != null && args.length > 0) {
                method.invoke(entity, args);
            } else {
                Class<?>[] parameterTypes = method.getParameterTypes();

                if (parameterTypes.length == 1 && parameterTypes[0] == int.class) {
                    //method.setAccessible(true);
                    method.invoke(entity, 0);
                } else {
                    args = new Object[parameterTypes.length];
                    //method.setAccessible(true);
                    method.invoke(entity, args);
                }/*from   ww w . j a v a  2 s.  c  o m*/
            }
        }
    }
}

From source file:com.facebook.config.ConfigAccessor.java

public <T> T getBean(String key, Class<? extends ExtractableBeanBuilder<T>> beanBuilderClass) {
    try {//  w  w w  .j a va2  s  .c o  m
        JSONObject jsonBean = get(key, null, new JSONObjectExtractor());
        ConfigAccessor jsonBeanAccessor = new ConfigAccessor(jsonBean);
        Object beanBuilder = beanBuilderClass.newInstance();

        for (Method m : beanBuilderClass.getMethods()) {
            if (m.getName().toLowerCase().startsWith("set")) {
                FieldExtractor extractor = m.getAnnotation(FieldExtractor.class);

                if (extractor != null) {
                    if (!Extractor.class.isAssignableFrom(extractor.extractorClass())) {
                        String message = String.format("extractor %s does not extend Extractor.class",
                                extractor);

                        LOG.error(message);

                        throw new ConfigException(message);
                    }

                    // if the parameter isn't optional check, or if it's optional
                    // and it is present; ie, if it's not optional and not there, let
                    // get() throw a ConfigException
                    if (!extractor.optional() || jsonBeanAccessor.hasKey(extractor.key())) {
                        Object value = jsonBeanAccessor.get(extractor.key(), null,
                                (Extractor) extractor.extractorClass().newInstance());

                        m.invoke(beanBuilder, value);
                    }
                } else {
                    LOG.warn("unable to find annotation for setter method " + m.getName());
                }
            }
        }

        return ((ExtractableBeanBuilder<T>) beanBuilder).build();
    } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
        throw new ConfigException(e);
    }
}

From source file:com.ancientprogramming.fixedformat4j.format.impl.FixedFormatManagerImpl.java

/**
 * @inheritDoc/*from   w w w.ja va 2  s.co  m*/
 */
public <T> String export(String template, T fixedFormatRecord) {
    StringBuffer result = new StringBuffer(template);
    Record record = getAndAssertRecordAnnotation(fixedFormatRecord.getClass());

    Class fixedFormatRecordClass = fixedFormatRecord.getClass();
    HashMap<Integer, String> foundData = new HashMap<Integer, String>(); // hashmap containing offset and data to write
    Method[] allMethods = fixedFormatRecordClass.getMethods();
    for (Method method : allMethods) {
        Field fieldAnnotation = method.getAnnotation(Field.class);
        Fields fieldsAnnotation = method.getAnnotation(Fields.class);
        if (fieldAnnotation != null) {
            String exportedData = exportDataAccordingFieldAnnotation(fixedFormatRecord, method,
                    fieldAnnotation);
            foundData.put(fieldAnnotation.offset(), exportedData);
        } else if (fieldsAnnotation != null) {
            Field[] fields = fieldsAnnotation.value();
            for (Field field : fields) {
                String exportedData = exportDataAccordingFieldAnnotation(fixedFormatRecord, method, field);
                foundData.put(field.offset(), exportedData);
            }
        }
    }

    Set<Integer> sortedoffsets = foundData.keySet();
    for (Integer offset : sortedoffsets) {
        String data = foundData.get(offset);
        appendData(result, record.paddingChar(), offset, data);
    }

    if (record.length() != -1) { //pad with paddingchar
        while (result.length() < record.length()) {
            result.append(record.paddingChar());
        }
    }
    return result.toString();
}

From source file:lineage2.gameserver.scripts.Scripts.java

/**
 * Method addHandlers.//from  www .j a v a2  s  . c om
 * @param clazz Class<?>
 */
private void addHandlers(Class<?> clazz) {
    try {
        for (Method method : clazz.getMethods()) {
            if (method.getName().contains("DialogAppend_")) {
                Integer id = Integer.parseInt(method.getName().substring(13));
                List<ScriptClassAndMethod> handlers = dialogAppends.get(id);
                if (handlers == null) {
                    handlers = new ArrayList<>();
                    dialogAppends.put(id, handlers);
                }
                handlers.add(new ScriptClassAndMethod(clazz.getName(), method.getName()));
            } else if (method.getName().contains("OnAction_")) {
                String name = method.getName().substring(9);
                onAction.put(name, new ScriptClassAndMethod(clazz.getName(), method.getName()));
            } else if (method.getName().contains("OnActionShift_")) {
                String name = method.getName().substring(14);
                onActionShift.put(name, new ScriptClassAndMethod(clazz.getName(), method.getName()));
            }
        }
    } catch (Exception e) {
        _log.error("", e);
    }
}

From source file:com.evolveum.midpoint.repo.sql.query2.definition.ClassDefinitionParser.java

private JpaEntityDefinition parseClass(Class jpaClass) {

    Class jaxbClass = getJaxbClassForEntity(jpaClass);
    JpaEntityDefinition entity = new JpaEntityDefinition(jpaClass, jaxbClass);
    LOGGER.trace("### {}", entity);

    addVirtualDefinitions(jpaClass, entity);
    Method[] methods = jpaClass.getMethods();

    for (Method method : methods) {
        String methodName = method.getName();
        if (Modifier.isStatic(method.getModifiers()) || "getClass".equals(methodName)
                || (!methodName.startsWith("is") && !methodName.startsWith("get"))
                || method.getAnnotation(NotQueryable.class) != null) {
            //it's not getter for queryable property
            continue;
        }/*  w  w w.  j a v a2  s  . c  o  m*/

        if (method.isAnnotationPresent(Transient.class)) {
            continue;
        }

        LOGGER.trace("# {}", method);

        JpaLinkDefinition linkDefinition;
        OwnerGetter ownerGetter = method.getAnnotation(OwnerGetter.class);
        if (ownerGetter != null) {
            String jpaName = getJpaName(method);
            JpaDataNodeDefinition nodeDefinition = new JpaEntityPointerDefinition(ownerGetter.ownerClass());
            // Owner is considered as not embedded, so we generate left outer join to access it
            // (instead of implicit inner join that would be used if we would do x.owner.y = '...')
            linkDefinition = new JpaLinkDefinition(new ParentPathSegment(), jpaName, null, false,
                    nodeDefinition);
        } else {
            linkDefinition = parseMethod(method);
        }
        entity.addDefinition(linkDefinition);
    }
    return entity;
}

From source file:com.github.kongchen.swagger.docgen.mavenplugin.SpringMavenDocumentSource.java

private Map<String, SpringResource> analyzeController(Class<?> clazz, Map<String, SpringResource> resourceMap,
        String description) throws ClassNotFoundException {

    for (int i = 0; i < clazz.getAnnotation(RequestMapping.class).value().length; i++) {
        String controllerMapping = clazz.getAnnotation(RequestMapping.class).value()[i];
        String resourceName = Utils.parseResourceName(clazz);
        for (Method m : clazz.getMethods()) {
            if (m.isAnnotationPresent(RequestMapping.class)) {
                RequestMapping methodReq = m.getAnnotation(RequestMapping.class);
                if (methodReq.value() == null || methodReq.value().length == 0
                        || Utils.parseResourceName(methodReq.value()[0]).equals("")) {
                    if (resourceName.length() != 0) {
                        String resourceKey = Utils.createResourceKey(resourceName,
                                Utils.parseVersion(controllerMapping));
                        if ((!(resourceMap.containsKey(resourceKey)))) {
                            resourceMap.put(resourceKey,
                                    new SpringResource(clazz, resourceName, resourceKey, description));
                        }/*  w ww . j a v a2 s . c o m*/
                        resourceMap.get(resourceKey).addMethod(m);
                    }
                }
            }
        }
    }
    clazz.getFields();
    clazz.getDeclaredFields(); //<--In case developer declares a field without an associated getter/setter.
    //this will allow NoClassDefFoundError to be caught before it triggers bamboo failure.

    return resourceMap;
}

From source file:com.xiovr.unibot.bot.impl.BotGameConfigImpl.java

private Properties createSettings(Class<?> clazz, String fn, String comment) {

    Properties props = new SortedProperties();
    try {//from  w  ww.j ava 2s  . c  o m
        //         File file = new File("/" + DIR_PATH + "/" + fn);
        File file = new File(fn);
        Method[] methods = clazz.getMethods();
        for (Method method : methods) {
            // Find setters
            if (method.getName().startsWith("set")) {
                if (method.isAnnotationPresent(Param.class)) {
                    Annotation annotation = method.getAnnotation(Param.class);
                    Param param = (Param) annotation;
                    if (param.name().equals("") || param.values().length == 0) {
                        throw new RuntimeException("Wrong param in class " + clazz.getCanonicalName()
                                + " with method " + method.getName());
                    }
                    Class<?>[] paramClazzes = method.getParameterTypes();
                    if (paramClazzes.length != 1) {
                        throw new RuntimeException("Error contract design in class " + clazz.getCanonicalName()
                                + " with method " + method.getName());
                    }
                    // Check param belongs to List
                    Class<?> paramClazz = paramClazzes[0];
                    if (List.class.isAssignableFrom(paramClazz)) {
                        // Oh, its array...
                        // May be its InetSocketAddress?
                        Type[] gpt = method.getGenericParameterTypes();
                        if (gpt[0] instanceof ParameterizedType) {
                            ParameterizedType type = (ParameterizedType) gpt[0];
                            Type[] typeArguments = type.getActualTypeArguments();

                            for (Type typeArgument : typeArguments) {
                                Class<?> classType = ((Class<?>) typeArgument);
                                if (InetSocketAddress.class.isAssignableFrom(classType)) {
                                    String[] vals = param.values();
                                    for (int i = 0; i < vals.length / 2; ++i) {
                                        props.setProperty(param.name() + "." + String.valueOf(i) + ".ip",
                                                vals[i * 2]);
                                        props.setProperty(param.name() + "." + String.valueOf(i) + ".port",
                                                vals[i * 2 + 1]);
                                    }
                                    props.setProperty(param.name() + ".count", String.valueOf(vals.length / 2));

                                } else {
                                    throw new RuntimeException("Settings param in class "
                                            + clazz.getCanonicalName() + " with method " + method.getName()
                                            + " not implementes yet");
                                }
                            }

                        }
                    } else if (paramClazz.isPrimitive()) {
                        props.setProperty(param.name(), param.values()[0]);

                    } else if (String.class.isAssignableFrom(paramClazz)) {

                        props.setProperty(param.name(), param.values()[0]);

                    } else {
                        throw new RuntimeException("Settings param in class " + clazz.getCanonicalName()
                                + " with method " + method.getName() + " not implemented yet");
                    }

                }
            }
        }

        BotUtils.saveProperties(file, props, comment);
    } catch (IOException e) {
        logger.error("Error save file " + fn);
    }
    return props;
}

From source file:cross.applicationContext.ReflectionApplicationContextGenerator.java

/**
 * Creates an xml element using the given document for element creation.
 *
 * @param generator/* w ww.  j  a v a  2 s  .co  m*/
 * @param document the document use for element creation
 * @param beanDescriptor
 * @return the modified element
 */
public static Element createElement(ReflectionApplicationContextGenerator generator, Document document,
        BeanDescriptor beanDescriptor) {
    Class<?> javaClass = beanDescriptor.clazz;
    System.out.println("Building bean element for " + javaClass.getName());
    //get the name of the class
    String className = javaClass.getSimpleName();

    //get the name of the package
    String packageName = javaClass.getPackage().getName();

    //create <bean /> element
    Element beanElement = document.createElement("bean");
    String classNameLower = toLowerCaseName(className);
    beanElement.setAttribute("id", classNameLower);
    String classAttr = (packageName == null) ? className : packageName + "." + className;
    beanElement.setAttribute("class", classAttr);
    beanElement.setAttribute("scope", beanDescriptor.scope);
    //constructors are not supported
    //get all the class' properties from the public fields and setter methods.

    for (Method method : javaClass.getMethods()) {
        checkMutableProperties(method, javaClass, beanDescriptor.obj, beanDescriptor.properties);
    }
    //sort by name
    Collections.sort(beanDescriptor.properties, new Comparator<ObjectProperty>() {
        @Override
        public int compare(ObjectProperty t, ObjectProperty t1) {
            return t.name.compareTo(t1.name);
        }
    });
    List<String> blackList = Arrays.asList("workflow", "progress", "cvResolver");
    //add all properties as <property /> elements
    for (ObjectProperty p : beanDescriptor.properties) {
        if (!blackList.contains(p.name)) {
            Element propertyElement = document.createElement("property");
            propertyElement.setAttribute("name", p.name);
            Comment propertyCommentElement = document
                    .createComment(AnnotationInspector.getDescriptionFor(javaClass, p.name));
            boolean append = true;
            if (p.type.startsWith("java.lang.")) {
                String shortType = p.type.substring("java.lang.".length());
                if (primitives.contains(shortType) || wrappers.contains(shortType)) {
                    propertyElement.setAttribute("value", p.value);
                }
            } else if (primitives.contains(p.type) || wrappers.contains(p.type)) {
                propertyElement.setAttribute("value", p.value);
            } else if ("Array".equals(p.type) || "List".equals(p.type) || "java.util.List".equals(p.type)) {
                Element listElement = document.createElement("list");
                String genericType = p.genericType;
                propertyElement.appendChild(listElement);
            } else if ("Set".equals(p.type) || "java.util.Set".equals(p.type)) {
                Element listElement = document.createElement("set");
                propertyElement.appendChild(listElement);
            } else if ("Map".equals(p.type) || "java.util.Map".equals(p.type)) {
                Element listElement = document.createElement("map");
                propertyElement.appendChild(listElement);
            } else if ("Properties".equals(p.type) || "java.util.Properties".equals(p.type)) {
                Element listElement = document.createElement("props");
                propertyElement.appendChild(listElement);
            } else {
                try {
                    //                    System.err.println("Skipping ref!");
                    Set<BeanDefinition> beanDefinitions = getImplementationsOf(Class.forName(p.type), "cross",
                            "maltcms", "net.sf.maltcms");
                    BeanDefinition first = null;
                    for (BeanDefinition bd : beanDefinitions) {
                        generator.addBean(bd.getBeanClassName());
                        if (first == null) {
                            first = bd;
                        }
                    }
                    if (first != null) {
                        String simpleName = first.getBeanClassName()
                                .substring(first.getBeanClassName().lastIndexOf(".") + 1);
                        propertyElement.setAttribute("ref",
                                generator.classToElement.get(toLowerCaseName(simpleName)).id);
                    }
                } catch (ClassNotFoundException ex) {
                    Logger.getLogger(ReflectionApplicationContextGenerator.class.getName()).log(Level.SEVERE,
                            null, ex);
                }
                append = true;
                //                    try {
                //                        generator.addBean(p.type);
                //                        Class<?> c = Class.forName(p.type);
                //                        List<Object> objects = generator.classToObject.get(c);
                //                        if (objects != null && !objects.isEmpty()) {
                //                            propertyElement.setAttribute("ref", generator.buildBeanElement(objects.get(0)).id);
                //                        } else {
                //                            append = false;
                //                        }
                //                    } catch (ClassNotFoundException ex) {
                //                        Logger.getLogger(ReflectionApplicationContextGenerator.class.getName()).log(Level.SEVERE, null, ex);
                //                    }

            }
            if (append) {
                beanElement.appendChild(propertyCommentElement);
                beanElement.appendChild(propertyElement);
            } else {
                beanElement.appendChild(propertyCommentElement);
                Comment comment = document.createComment("<property name=\"" + p.name + "\" ref=\"\"/>");
                beanElement.appendChild(comment);
            }
        }
    }
    return beanElement;
}