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:org.apache.struts2.convention.DefaultClassFinder.java

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

        Package aPackage = clazz.getPackage();
        if (aPackage != null && !packages.contains(aPackage)) {
            infos.add(new PackageInfo(aPackage));
            packages.add(aPackage);// w ww.  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:com.betfair.testing.utils.cougar.helpers.CougarHelpers.java

private String[] getOrderedMethodNamesFromClass(String classPath) throws ClassNotFoundException {

    Class baseline = Class.forName(classPath);
    Method[] methods = baseline.getDeclaredMethods();

    String[] methodNames = new String[methods.length];
    for (int i = 0; i < methods.length; i++) {
        methodNames[i] = methods[i].getName();
    }/*from   w  w w . j a v a 2  s  .c  om*/
    Arrays.sort(methodNames);

    return methodNames;
}

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

/**
 * Instantiates a new snippet dependency.
 *
 * @param pJavaClass/*from  www  .  ja  va2  s .c  o m*/
 *            the Java class
 * @param classLoader
 *            the class loader for loading snippet project classes
 * @throws ValidatorException
 *             if validation has failed
 */
SnippetDependency(final Class<?> pJavaClass, final ClassLoader classLoader) throws ValidatorException {
    Validate.notNull(pJavaClass, "The Java class must not be null");
    javaClass = pJavaClass;

    // start validaton
    GeneralValidator validator = new GeneralValidator(SnippetDependency.class);

    // validate class
    // check: only @SetteDependency SETTE annotation
    AnnotationMap classAnns = SetteAnnotationUtils.getSetteAnnotations(pJavaClass);

    if (classAnns.size() != 1 || classAnns.get(SetteDependency.class) == null) {
        ClassValidator v = new ClassValidator(pJavaClass);
        v.addException("The class must not only have the @" + SetteDependency.class.getSimpleName()
                + " SETTE annotation");
        validator.addChildIfInvalid(v);
    }

    // validate methods
    // check: no SETTE annotations
    for (Method method : pJavaClass.getDeclaredMethods()) {
        if (method.isSynthetic()) {
            // skip synthetic methods
            continue;
        }

        if (!SetteAnnotationUtils.getSetteAnnotations(method).isEmpty()) {
            MethodValidator v = new MethodValidator(method);
            v.addException("The method must not have " + "any SETTE annotations");
            validator.addChildIfInvalid(v);
        }
    }

    validator.validate();
}

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

private Set<Method> getWritableNormalMethods(final Class<?> thisPojoClass) throws NotFoundException {
    final CtClass ctClass = ctPool.get(thisPojoClass.getName());
    final Set<CtMethod> ctMethodSet = new LinkedHashSet<>(); // Gets
                                                             // collected
    final Set<Method> methodSet = 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;
        }/*from  www.j a  va  2  s . c o m*/
        if (Modifier.isPublic(method.getModifiers())
                && setMethodNamePattern.matcher(method.getName()).matches()) {
            methodSet.add(method);
        }
        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 methodSet;
}

From source file:de.codesourcery.eve.skills.util.SpringBeanInjector.java

private void doInjectDependencies(Object obj)
        throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {

    Class<?> currentClasz = obj.getClass();
    do {/*from w ww.jav  a  2 s  .  com*/
        // inject fields
        for (Field f : currentClasz.getDeclaredFields()) {

            final int m = f.getModifiers();
            if (Modifier.isStatic(m) || Modifier.isFinal(m)) {
                continue;
            }

            final Resource annot = f.getAnnotation(Resource.class);
            if (annot != null) {
                if (!f.isAccessible()) {
                    f.setAccessible(true);
                }

                if (log.isTraceEnabled()) {
                    log.trace("doInjectDependencies(): Setting field " + f.getName() + " with bean '"
                            + annot.name() + "'");
                }
                f.set(obj, getBean(annot.name()));
            }
        }

        // inject methods
        for (Method method : currentClasz.getDeclaredMethods()) {

            final int m = method.getModifiers();
            if (Modifier.isStatic(m) || Modifier.isAbstract(m)) {
                continue;
            }

            if (method.getParameterTypes().length != 1) {
                continue;
            }

            if (!method.getName().startsWith("set")) {
                continue;
            }

            final Resource annot = method.getAnnotation(Resource.class);
            if (annot != null) {
                if (!method.isAccessible()) {
                    method.setAccessible(true);
                }

                if (log.isTraceEnabled()) {
                    log.trace("doInjectDependencies(): Invoking setter method " + method.getName()
                            + " with bean '" + annot.name() + "'");
                }

                method.invoke(obj, getBean(annot.name()));
            }
        }

        currentClasz = currentClasz.getSuperclass();

    } while (currentClasz != null);
}

From source file:com.opensymphony.xwork2.validator.AnnotationValidationConfigurationBuilder.java

public List<ValidatorConfig> buildAnnotationClassValidatorConfigs(Class aClass) {

    List<ValidatorConfig> result = new ArrayList<ValidatorConfig>();

    List<ValidatorConfig> temp = processAnnotations(aClass);
    if (temp != null) {
        result.addAll(temp);/*www. j a v a 2s . co  m*/
    }

    Method[] methods = aClass.getDeclaredMethods();

    if (methods != null) {
        for (Method method : methods) {
            temp = processAnnotations(method);
            if (temp != null) {
                result.addAll(temp);
            }
        }
    }

    return result;

}

From source file:edu.usu.sdl.openstorefront.doc.JaxrsProcessor.java

public static APIResourceModel processRestClass(Class resource, String rootPath) {
    APIResourceModel resourceModel = new APIResourceModel();

    resourceModel.setClassName(resource.getName());
    resourceModel.setResourceName(/*from  w w  w . j  a  v  a 2s .  c om*/
            String.join(" ", StringUtils.splitByCharacterTypeCamelCase(resource.getSimpleName())));

    APIDescription aPIDescription = (APIDescription) resource.getAnnotation(APIDescription.class);
    if (aPIDescription != null) {
        resourceModel.setResourceDescription(aPIDescription.value());
    }

    Path path = (Path) resource.getAnnotation(Path.class);
    if (path != null) {
        resourceModel.setResourcePath(rootPath + "/" + path.value());
    }

    RequireAdmin requireAdmin = (RequireAdmin) resource.getAnnotation(RequireAdmin.class);
    if (requireAdmin != null) {
        resourceModel.setRequireAdmin(true);
    }

    //class parameters
    mapParameters(resourceModel.getResourceParams(), resource.getDeclaredFields());

    //methods
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
    objectMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
    int methodId = 0;
    for (Method method : resource.getDeclaredMethods()) {

        APIMethodModel methodModel = new APIMethodModel();
        methodModel.setId(methodId++);

        //rest method
        List<String> restMethods = new ArrayList<>();
        GET getMethod = (GET) method.getAnnotation(GET.class);
        POST postMethod = (POST) method.getAnnotation(POST.class);
        PUT putMethod = (PUT) method.getAnnotation(PUT.class);
        DELETE deleteMethod = (DELETE) method.getAnnotation(DELETE.class);
        if (getMethod != null) {
            restMethods.add("GET");
        }
        if (postMethod != null) {
            restMethods.add("POST");
        }
        if (putMethod != null) {
            restMethods.add("PUT");
        }
        if (deleteMethod != null) {
            restMethods.add("DELETE");
        }
        methodModel.setRestMethod(String.join(",", restMethods));

        if (restMethods.isEmpty()) {
            //skip non-rest methods
            continue;
        }

        //produces
        Produces produces = (Produces) method.getAnnotation(Produces.class);
        if (produces != null) {
            methodModel.setProducesTypes(String.join(",", produces.value()));
        }

        //consumes
        Consumes consumes = (Consumes) method.getAnnotation(Consumes.class);
        if (consumes != null) {
            methodModel.setConsumesTypes(String.join(",", consumes.value()));
        }

        aPIDescription = (APIDescription) method.getAnnotation(APIDescription.class);
        if (aPIDescription != null) {
            methodModel.setDescription(aPIDescription.value());
        }

        path = (Path) method.getAnnotation(Path.class);
        if (path != null) {
            methodModel.setMethodPath(path.value());
        }

        requireAdmin = (RequireAdmin) method.getAnnotation(RequireAdmin.class);
        if (requireAdmin != null) {
            methodModel.setRequireAdmin(true);
        }

        try {
            if (!(method.getReturnType().getSimpleName().equalsIgnoreCase(Void.class.getSimpleName()))) {
                APIValueModel valueModel = new APIValueModel();
                DataType dataType = (DataType) method.getAnnotation(DataType.class);

                boolean addResponseObject = true;
                if ("javax.ws.rs.core.Response".equals(method.getReturnType().getName()) && dataType == null) {
                    addResponseObject = false;
                }

                if (addResponseObject) {
                    valueModel.setValueObjectName(method.getReturnType().getSimpleName());
                    ReturnType returnType = (ReturnType) method.getAnnotation(ReturnType.class);
                    Class returnTypeClass;
                    if (returnType != null) {
                        returnTypeClass = returnType.value();
                    } else {
                        returnTypeClass = method.getReturnType();
                    }

                    if (!"javax.ws.rs.core.Response".equals(method.getReturnType().getName())) {
                        if (ReflectionUtil.isCollectionClass(method.getReturnType()) == false) {
                            try {
                                valueModel.setValueObject(
                                        objectMapper.writeValueAsString(returnTypeClass.newInstance()));
                                mapValueField(valueModel.getValueFields(),
                                        ReflectionUtil.getAllFields(returnTypeClass).toArray(new Field[0]));
                                mapComplexTypes(valueModel.getAllComplexTypes(),
                                        ReflectionUtil.getAllFields(returnTypeClass).toArray(new Field[0]),
                                        false);

                                aPIDescription = (APIDescription) returnTypeClass
                                        .getAnnotation(APIDescription.class);
                                if (aPIDescription != null) {
                                    valueModel.setValueDescription(aPIDescription.value());
                                }
                            } catch (InstantiationException iex) {
                                log.log(Level.WARNING, MessageFormat.format(
                                        "Unable to instantiated type: {0} make sure the type is not abstract.",
                                        returnTypeClass));
                            }
                        }
                    }

                    if (dataType != null) {
                        String typeName = dataType.value().getSimpleName();
                        if (StringUtils.isNotBlank(dataType.actualClassName())) {
                            typeName = dataType.actualClassName();
                        }
                        valueModel.setTypeObjectName(typeName);
                        try {
                            valueModel.setTypeObject(
                                    objectMapper.writeValueAsString(dataType.value().newInstance()));
                            mapValueField(valueModel.getTypeFields(),
                                    ReflectionUtil.getAllFields(dataType.value()).toArray(new Field[0]));
                            mapComplexTypes(valueModel.getAllComplexTypes(),
                                    ReflectionUtil.getAllFields(dataType.value()).toArray(new Field[0]), false);

                            aPIDescription = (APIDescription) dataType.value()
                                    .getAnnotation(APIDescription.class);
                            if (aPIDescription != null) {
                                valueModel.setTypeDescription(aPIDescription.value());
                            }

                        } catch (InstantiationException iex) {
                            log.log(Level.WARNING, MessageFormat.format(
                                    "Unable to instantiated type: {0} make sure the type is not abstract.",
                                    dataType.value()));
                        }
                    }

                    methodModel.setResponseObject(valueModel);
                }
            }
        } catch (IllegalAccessException | JsonProcessingException ex) {
            log.log(Level.WARNING, null, ex);
        }

        //method parameters
        mapMethodParameters(methodModel.getMethodParams(), method.getParameters());

        //Handle Consumed Objects
        mapConsumedObjects(methodModel, method.getParameters());

        resourceModel.getMethods().add(methodModel);
    }
    Collections.sort(resourceModel.getMethods(), new ApiMethodComparator<>());
    return resourceModel;
}

From source file:iterator.test.matchers.type.annotation.AnnotationMap.java

private AnnotationMap(Class<A> annotationClass, A annotation) {
    this.annotationClass = annotationClass;
    Method[] methods = annotationClass.getDeclaredMethods();
    for (Method m : methods) {
        String memberName = m.getName();
        MemberValue<?> mv = MemberValueFactory.forMember(memberName, annotation, annotationClass);
        members.put(memberName, mv);/*w  ww  .ja  va 2s .com*/
    }
    memberNames = unmodifiableSet(members.keySet());
}

From source file:jenkins.scm.api.SCMHeadMixinEqualityGenerator.java

/**
 * Creates the {@link SCMHeadMixin.Equality} instance.
 *
 * @param type the {@link SCMHead} type to create the instance for.
 * @return the {@link SCMHeadMixin.Equality} instance.
 *//*  w w w .  j av a  2 s  . co m*/
@NonNull
private SCMHeadMixin.Equality create(@NonNull Class<? extends SCMHead> type) {
    Map<String, Method> properties = new TreeMap<String, Method>();
    for (Class clazz : (List<Class>) ClassUtils.getAllInterfaces(type)) {
        if (!SCMHeadMixin.class.isAssignableFrom(clazz)) {
            // not a mix-in
            continue;
        }
        if (SCMHeadMixin.class == clazz) {
            // no need to check this by reflection
            continue;
        }
        if (!Modifier.isPublic(clazz.getModifiers())) {
            // not public
            continue;
        }
        // this is a mixin interface, only look at declared properties;
        for (Method method : clazz.getDeclaredMethods()) {
            if (method.getReturnType() == Void.class) {
                // nothing to do with us
                continue;
            }
            if (!Modifier.isPublic(method.getModifiers())) {
                // should never get here
                continue;
            }
            if (Modifier.isStatic(method.getModifiers())) {
                // might get here with Java 8
                continue;
            }
            if (method.getParameterTypes().length != 0) {
                // not a property
                continue;
            }
            String name = method.getName();
            if (!name.matches("^((is[A-Z0-9_].*)|(get[A-Z0-9_].*))$")) {
                // not a property
                continue;
            }
            if (name.startsWith("is")) {
                name = "" + Character.toLowerCase(name.charAt(2))
                        + (name.length() > 3 ? name.substring(3) : "");
            } else {
                name = "" + Character.toLowerCase(name.charAt(3))
                        + (name.length() > 4 ? name.substring(4) : "");
            }
            if (properties.containsKey(name)) {
                // a higher priority interface already defined the method
                continue;
            }
            properties.put(name, method);
        }
    }
    if (properties.isEmpty()) {
        // no properties to consider
        return new ConstantEquality();
    }
    if (forceReflection) {
        return new ReflectiveEquality(properties.values().toArray(new Method[properties.size()]));
    }
    // now we define the class
    ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES);
    String name = SCMHeadMixin.class.getPackage().getName() + ".internal." + type.getName();

    // TODO Move to 1.7 opcodes once baseline 1.612+
    cw.visit(Opcodes.V1_6, ACC_PUBLIC, name.replace('.', '/'), null, Type.getInternalName(Object.class),
            new String[] { Type.getInternalName(SCMHeadMixin.Equality.class) });
    generateDefaultConstructor(cw);
    generateEquals(cw, properties.values());
    byte[] image = cw.toByteArray();

    Class<? extends SCMHeadMixin.Equality> c = defineClass(name, image, 0, image.length)
            .asSubclass(SCMHeadMixin.Equality.class);

    try {
        return c.newInstance();
    } catch (InstantiationException e) {
        // fallback to reflection
    } catch (IllegalAccessException e) {
        // fallback to reflection
    }
    return new ReflectiveEquality(properties.values().toArray(new Method[properties.size()]));

}

From source file:com.opengsn.controller.client.ControllerClient.java

/**
 * Use the commandline args to invoke the proper service client and
 * operation using Reflection/*from w  w  w  . ja v  a 2  s  .c  om*/
 * 
 * @param args
 */
private void process(String[] args) {

    Class<?> c = this.getClass();
    try {
        // Class<?> c =
        // Class.forName("com.greenstarnetwork.controller.client.ControllerWrapper");

        // Use reflection to call the service and operation that was given
        // from the command line
        Object obj = c.newInstance();
        @SuppressWarnings("rawtypes")
        Class[] argTypes = new Class[] { String[].class };
        Method m = c.getDeclaredMethod(args[0], argTypes);

        String[] methodArgs = Arrays.copyOfRange(args, 1, args.length);
        System.out.println("invoking Operation: " + c.getName() + "." + m.getName());
        m.invoke(obj, (Object) methodArgs);

    } catch (NoSuchMethodException e) {
        System.out.println("Invalid Operation: " + args[1]);
        System.out.println("Operations for the " + c.getName() + ": ");
        Method[] allMethods = c.getDeclaredMethods();
        for (Method m : allMethods) {
            System.out.println("  " + m.getName());
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

}