Example usage for java.lang Class getDeclaredMethods

List of usage examples for java.lang Class getDeclaredMethods

Introduction

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

Prototype

@CallerSensitive
public Method[] getDeclaredMethods() throws SecurityException 

Source Link

Document

Returns an array containing Method objects reflecting all the declared methods of the class or interface represented by this Class object, including public, protected, default (package) access, and private methods, but excluding inherited methods.

Usage

From source file:com.github.venkateshamurthy.designpatterns.builders.FluentBuilders.java

/**
 * Gets a list of writable methods / mutator methods. <br>
 * /*from  w ww .  j  a va2s  .c o  m*/
 * @param thisPojoClass
 *            for which mutator methods must be found
 * @return List of {@link CtMethod}
 * @throws NotFoundException
 *             when thisPojoClass is not found
 */
private Set<CtMethod> getWritableMethods(final Class<?> thisPojoClass) throws NotFoundException {
    final CtClass ctClass = ctPool.get(thisPojoClass.getName());
    final Set<CtMethod> ctMethodSet = new LinkedHashSet<>(); // Gets
                                                             // collected
    final Set<Class<?>> propTypes = getPropertyClassTypes(thisPojoClass, ctClass, ctMethodSet);

    for (Method method : thisPojoClass.getDeclaredMethods()) {
        if (method.isSynthetic()) {
            LOGGER.warning(method.getName() + " is synthetically added, so ignoring");
            continue;
        }
        final CtMethod ctMethod = ctClass.getDeclaredMethod(method.getName());
        if (Modifier.isPublic(method.getModifiers()) && setMethodNamePattern.matcher(method.getName()).matches()
                && !ctMethodSet.contains(ctMethod)) {
            // Make sure the types u get from method is really is of a field
            // type
            boolean isAdded = /*
                               * propTypes.containsAll(Arrays.asList(method.
                               * getParameterTypes())) &&
                               */ctMethodSet.add(ctMethod);
            if (!isAdded) {
                LOGGER.warning(method.getName() + " is not added");
            }
        }
    }
    return ctMethodSet;
}

From source file:org.castor.jaxb.reflection.FieldAnnotationProcessingServiceTest.java

@Test
public void testProcessAnnotations() {
    Class<NotASingleField> clazz = NotASingleField.class;
    Assert.assertFalse(clazz.isEnum());/*from   www.  j  a  v a  2 s . c  o m*/
    Assert.assertNotNull(fieldAnnotationProcessingService);
    Field[] fields = clazz.getDeclaredFields();
    for (int i = 0; i < fields.length; i++) {
        Field field = fields[i];
        JaxbFieldNature fi = new JaxbFieldNature(new FieldInfo(field.getName()));
        fieldAnnotationProcessingService.processAnnotations(fi, field.getAnnotations());
    }
    Method[] methods = clazz.getDeclaredMethods();
    for (int i = 0; i < methods.length; i++) {
        Method method = methods[i];
        JaxbFieldNature fi = new JaxbFieldNature(new FieldInfo(method.getName()));
        fieldAnnotationProcessingService.processAnnotations(fi, method.getAnnotations());
    }
}

From source file:com.kjt.service.common.SoafwTesterMojo.java

/**
 * //from   w w  w. ja v a2s  .c  om
 * @param className 
 */
private void appendTest(String className) {
    /**
     * ?? ?public
     * ?MojoExecutionException??????
     */
    try {

        Map<String, Integer> methodCnt = new HashMap<String, Integer>();
        boolean hasmethod = false;

        Map<String, String> methodDefs = new HashMap<String, String>();
        Class cls = cl.loadClass(className);// 
        Class[] inters = cls.getInterfaces();
        int len = 0;
        if (inters == null || (len = inters.length) == 0) {
            return;
        }
        for (int i = 0; i < len; i++) {

            Class interCls = inters[i];

            this.getLog().info("@interface: " + interCls.getName());

            String name = project.getName();

            Method[] methods = null;

            if (name.endsWith("-dao")) {
                methods = interCls.getDeclaredMethods();
            } else {
                methods = interCls.getMethods();
            }

            int mlen = 0;
            if (methods != null && (mlen = methods.length) > 0) {

                StringBuffer methodBuf = new StringBuffer();

                for (int m = 0; m < mlen; m++) {
                    Method method = methods[m];
                    int modf = method.getModifiers();
                    if (modf == 1025) {// ??
                        hasmethod = true;
                        /**
                         * ??????Test ???=??+Test
                         * ??:basedPath+File.separator
                         * +src+File.separator+test+File.separator
                         * +pkg+definesArray[i]+Test+.java
                         */
                        if (methodCnt.containsKey(method.getName())) {
                            methodCnt.put(method.getName(), methodCnt.get(method.getName()) + 1);
                        } else {
                            methodCnt.put(method.getName(), 0);
                        }
                        int cnt = methodCnt.get(method.getName());

                        addMethod(methodDefs, methodBuf, method, cnt);
                    }
                }
            }
        }

        Class tstCls = cl.loadClass(className + "Test");// 

        Method[] methods = tstCls.getDeclaredMethods();
        len = methods == null ? 0 : methods.length;
        this.getLog().info("" + tstCls.getSimpleName() + "?" + len);

        /**
         * ??public
         */
        for (int m = 0; m < len; m++) {

            Method method = methods[m];
            SoaFwTest test = method.getAnnotation(SoaFwTest.class);
            if (test == null) {
                this.getLog()
                        .info(tstCls.getSimpleName() + " method " + method.getName() + "SoaFwTest");
                continue;
            }

            String id = test.id();

            if (methodDefs.containsKey(id)) {
                methodDefs.remove(id);
            }
        }

        if ((len = methodDefs.size()) == 0) {
            return;
        }

        String[] methodImpls = new String[len];
        methodDefs.keySet().toArray(methodImpls);
        // TODO  ???
        this.getLog().info("???");

        StringBuilder src = new StringBuilder();

        String srcs = readTestSrc(className);

        int index = srcs.lastIndexOf("}");

        this.getLog().info(srcs);
        this.getLog().info("lastIndexOf(}):" + index);
        String impls = srcs.substring(0, index - 1);

        src.append(impls);

        src.append("\n");

        StringBuilder appends = new StringBuilder();
        this.getLog().info("?");
        for (int i = 0; i < len; i++) {
            String methodId = methodImpls[i];
            String method = methodDefs.get(methodId);
            appends.append(method);
            appends.append("\n");
        }

        src.append(appends.toString());

        src.append("}");

        Package pkg = tstCls.getPackage();
        String pkgName = pkg.getName();
        String pkgPath = pkgName.replace(".", File.separator);

        String testBaseSrcPath = basedPath + File.separator + "src" + File.separator + "test" + File.separator
                + "java";
        String testSrcFullPath = testBaseSrcPath + File.separator + pkgPath;

        write(testSrcFullPath, tstCls.getSimpleName() + ".java", src.toString());

    } catch (Exception e) {
        this.getLog().error(e);
    } catch (Error er) {
        this.getLog().error(er);
    }
}

From source file:com.p5solutions.core.utils.ReflectionUtility.java

/**
 * Find method.//from   w w w.ja  v a 2  s  .  c  o  m
 * 
 * @param clazz
 *          the clazz
 * @param methodName
 *          the method name
 * @param ignoreParamSearch
 *          the ignore param search
 * @param paramTypes
 *          the param types
 * @return the method
 */
public static Method findMethod(Class<?> clazz, String methodName, boolean ignoreParamSearch,
        Class<?>... paramTypes) {

    Method method = null;

    // Iterate all declared methods of the class
    for (Method m : clazz.getDeclaredMethods()) {

        // continue to next method, if name does not match
        if (!m.getName().equals(methodName)) {
            continue;
        }

        // only check the parameter lengths and
        // types if ignoreParamSearch is false
        if (!ignoreParamSearch && checkParams(m, paramTypes)) {
            method = m; // set the returning result
            break; // exit the loop
        } else if (ignoreParamSearch && method != null) {
            throw new RuntimeException(
                    "Multiple methods found, please specify a list of parameter types to refine your method search.");
        }

        method = m;
    }

    /* if the method is still null, then check its superclass */
    if (method == null) {
        Class<?> superClazz = clazz.getSuperclass();

        // if we've hit the base object?
        if (!superClazz.equals(Object.class)) {

            // recursively look for the method
            method = findMethod( //
                    superClazz, //
                    methodName, //
                    ignoreParamSearch, //
                    paramTypes);
        }
    }

    return method;
}

From source file:hu.bme.mit.sette.common.model.snippet.Snippet.java

/**
 * Parses the methods which should be considered in coverage.
 *
 * @param annotation/*from   www .  j a  v a2  s . c om*/
 *            the {@link SetteIncludeCoverage} annotation
 * @param v
 *            a {@link MethodValidator}
 * @param classLoader
 *            the class loader for loading snippet project classes
 */
private void parseIncludedMethods(final SetteIncludeCoverage annotation, final MethodValidator v,
        final ClassLoader classLoader) {
    if (annotation == null) {
        return;
    }

    Class<?>[] includedClasses = annotation.classes();
    String[] includedMethodStrings = annotation.methods();
    boolean shouldParse = true; // only parse if no validation error

    // check the arrays: not empty, no null element, same lengths
    if (ArrayUtils.isEmpty(includedClasses)) {
        v.addException("The included class list must not be empty");
        shouldParse = false;
    }

    if (ArrayUtils.contains(includedClasses, null)) {
        v.addException("The included class list " + "must not contain null elements");
        shouldParse = false;
    }

    if (ArrayUtils.isEmpty(includedMethodStrings)) {
        v.addException("The included method list must not be empty");
        shouldParse = false;
    }

    if (ArrayUtils.contains(includedMethodStrings, null)) {
        v.addException("The included method list " + "must not contain null elements");
        shouldParse = false;
    }

    if (!ArrayUtils.isSameLength(includedClasses, includedMethodStrings)) {
        v.addException("The included class list and method list " + "must have the same length");
        shouldParse = false;
    }

    if (shouldParse) {
        // check and add methods
        for (int i = 0; i < includedClasses.length; i++) {
            Class<?> includedClass = includedClasses[i];
            String includedMethodString = includedMethodStrings[i].trim();

            if (includedMethodString.equals("*")) {
                // add all non-synthetic constructors
                for (Constructor<?> c : includedClass.getDeclaredConstructors()) {
                    if (!c.isSynthetic()) {
                        addIncludedConstructor(c, v);
                    }
                }
                // add all non-synthetic methods
                for (Method m : includedClass.getDeclaredMethods()) {
                    if (!m.isSynthetic()) {
                        addIncludedMethod(m, v);
                    }
                }
            } else {
                parseIncludedMethod(includedClass, includedMethodString, v, classLoader);
            }
        }
    }
}

From source file:com.link_intersystems.lang.reflect.criteria.MemberCriteria.java

protected List<Member> getSortedMembers(Class<?> currentClass) {
    List<Member> memberList = new ArrayList<Member>();
    for (Class<?> memberType : memberTypes) {
        Member[] members = null;//from   ww  w .  j  ava 2 s.  c o m
        if (Constructor.class.equals(memberType)) {
            members = currentClass.getDeclaredConstructors();
        } else if (Method.class.equals(memberType)) {
            members = currentClass.getDeclaredMethods();
        } else if (Field.class.equals(memberType)) {
            members = currentClass.getDeclaredFields();
        }
        if (members != null) {
            List<Member> asList = Arrays.asList(members);
            memberList.addAll(asList);
        }
    }

    Collections.sort(memberList, iterateOrderComparator);
    return memberList;
}

From source file:com.opensymphony.xwork2.util.finder.DefaultClassFinder.java

public DefaultClassFinder(List<Class> classes) {
    this.classLoaderInterface = null;
    List<Info> infos = new ArrayList<Info>();
    List<Package> packages = new ArrayList<Package>();
    for (Class clazz : classes) {

        Package aPackage = clazz.getPackage();
        if (aPackage != null && !packages.contains(aPackage)) {
            infos.add(new PackageInfo(aPackage));
            packages.add(aPackage);/*from ww  w . j a va  2s. c om*/
        }

        ClassInfo classInfo = new ClassInfo(clazz, this);
        infos.add(classInfo);
        classInfos.put(classInfo.getName(), classInfo);
        for (Method method : clazz.getDeclaredMethods()) {
            infos.add(new MethodInfo(classInfo, method));
        }

        for (Constructor constructor : clazz.getConstructors()) {
            infos.add(new MethodInfo(classInfo, constructor));
        }

        for (Field field : clazz.getDeclaredFields()) {
            infos.add(new FieldInfo(classInfo, field));
        }
    }

    for (Info info : infos) {
        for (AnnotationInfo annotation : info.getAnnotations()) {
            List<Info> annotationInfos = getAnnotationInfos(annotation.getName());
            annotationInfos.add(info);
        }
    }
}

From source file:org.apache.struts2.convention.Java8ClassFinder.java

public Java8ClassFinder(List<Class> classes) {
    this.classLoaderInterface = null;
    List<Info> infos = new ArrayList<Info>();
    List<Package> packages = new ArrayList<Package>();
    for (Class clazz : classes) {

        Package aPackage = clazz.getPackage();
        if (aPackage != null && !packages.contains(aPackage)) {
            infos.add(new PackageInfo(aPackage));
            packages.add(aPackage);/*from ww w . j  a  v a2s .  c o  m*/
        }

        ClassInfo classInfo = new ClassInfo(clazz, this);
        infos.add(classInfo);
        classInfos.put(classInfo.getName(), classInfo);
        for (Method method : clazz.getDeclaredMethods()) {
            infos.add(new MethodInfo(classInfo, method));
        }

        for (Constructor constructor : clazz.getConstructors()) {
            infos.add(new MethodInfo(classInfo, constructor));
        }

        for (Field field : clazz.getDeclaredFields()) {
            infos.add(new FieldInfo(classInfo, field));
        }
    }

    for (Info info : infos) {
        for (AnnotationInfo annotation : info.getAnnotations()) {
            List<Info> annotationInfos = getAnnotationInfos(annotation.getName());
            annotationInfos.add(info);
        }
    }
}

From source file:org.apache.camel.component.bean.BeanInfo.java

/**
 * Introspects the given class/*from w w  w  .  j av a  2 s  .c  om*/
 *
 * @param clazz the class
 */
protected void introspect(Class<?> clazz) {
    // get the target clazz as it could potentially have been enhanced by CGLIB etc.
    clazz = getTargetClass(clazz);

    if (LOG.isTraceEnabled()) {
        LOG.trace("Introspecting class: " + clazz);
    }

    Method[] methods = clazz.getDeclaredMethods();
    for (Method method : methods) {
        boolean valid = isValidMethod(clazz, method);
        if (LOG.isTraceEnabled()) {
            LOG.trace("Method:  " + method + " is valid: " + valid);
        }
        if (valid) {
            introspect(clazz, method);
        }
    }

    Class<?> superclass = clazz.getSuperclass();
    if (superclass != null && !superclass.equals(Object.class)) {
        introspect(superclass);
    }
}

From source file:com.haulmont.cuba.core.config.AppPropertiesLocator.java

protected List<AppPropertyEntity> findDatabaseStoredProperties(Set<Class> configInterfaces) {
    List<AppPropertyEntity> result = new ArrayList<>();

    Map<Method, Object> propertyMethods = new HashMap<>();
    for (Class configInterface : configInterfaces) {
        if (configInterface.getClassLoader() != getClass().getClassLoader()) {
            // happens when deployed to single WAR with separate classloaders for core and web
            continue;
        }/*from  w  w  w. jav  a 2 s.  c  o  m*/
        Config config = configuration.getConfig(configInterface);
        boolean interfaceSourceIsDb = false;
        Source sourceAnn = (Source) configInterface.getAnnotation(Source.class);
        if (sourceAnn != null && sourceAnn.type() == SourceType.DATABASE) {
            interfaceSourceIsDb = true;
        }
        Method[] declaredMethods = configInterface.getDeclaredMethods();
        for (Method method : declaredMethods) {
            if (method.getName().startsWith("get")) {
                Source methodSourceAnn = method.getAnnotation(Source.class);
                if ((methodSourceAnn == null && interfaceSourceIsDb)
                        || (methodSourceAnn != null && methodSourceAnn.type() == SourceType.DATABASE)) {
                    propertyMethods.put(method, config);
                }
            }
        }
    }

    List<com.haulmont.cuba.core.entity.Config> dbContent = loadDbContent();

    for (Map.Entry<Method, Object> entry : propertyMethods.entrySet()) {
        Method method = entry.getKey();
        Property propertyAnn = method.getAnnotation(Property.class);
        if (propertyAnn == null)
            continue;

        String name = propertyAnn.value();
        AppPropertyEntity entity = new AppPropertyEntity();
        entity.setName(name);
        entity.setDefaultValue(getDefaultValue(method));
        entity.setCurrentValue(getCurrentValue(method, entry.getValue()));
        entity.setOverridden(StringUtils.isNotEmpty(AppContext.getProperty(name)));
        entity.setSecret(method.getAnnotation(Secret.class) != null);
        if (!entity.getOverridden()) {
            assignLastUpdated(entity, dbContent);
        }
        setDataType(method, entity);
        result.add(entity);
    }

    return result;
}