Example usage for java.lang.reflect Method getModifiers

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

Introduction

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

Prototype

@Override
public int getModifiers() 

Source Link

Usage

From source file:org.gradle.model.internal.manage.schema.extract.StructStrategy.java

public <R> ModelSchemaExtractionResult<R> extract(final ModelSchemaExtractionContext<R> extractionContext,
        final ModelSchemaCache cache) {
    ModelType<R> type = extractionContext.getType();
    Class<? super R> clazz = type.getRawClass();
    if (clazz.isAnnotationPresent(Managed.class)) {
        validateType(type, extractionContext);

        Iterable<Method> methods = Arrays.asList(clazz.getMethods());
        if (!clazz.isInterface()) {
            methods = filterIgnoredMethods(methods);
        }//from   ww w.  j a va2s  .c o m
        ImmutableListMultimap<String, Method> methodsByName = Multimaps.index(methods,
                new Function<Method, String>() {
                    public String apply(Method method) {
                        return method.getName();
                    }
                });

        ensureNoOverloadedMethods(extractionContext, methodsByName);

        List<ModelProperty<?>> properties = Lists.newLinkedList();
        List<Method> handled = Lists.newArrayListWithCapacity(clazz.getMethods().length);
        ReturnTypeSpecializationOrdering returnTypeSpecializationOrdering = new ReturnTypeSpecializationOrdering();

        for (String methodName : methodsByName.keySet()) {
            if (methodName.startsWith("get") && !methodName.equals("get")) {
                ImmutableList<Method> getterMethods = methodsByName.get(methodName);

                // The overload check earlier verified that all methods for are equivalent for our purposes
                // So, taking the first one with the most specialized return type is fine.
                Method sampleMethod = returnTypeSpecializationOrdering.max(getterMethods);

                boolean abstractGetter = Modifier.isAbstract(sampleMethod.getModifiers());

                if (sampleMethod.getParameterTypes().length != 0) {
                    throw invalidMethod(extractionContext, "getter methods cannot take parameters",
                            sampleMethod);
                }

                Character getterPropertyNameFirstChar = methodName.charAt(3);
                if (!Character.isUpperCase(getterPropertyNameFirstChar)) {
                    throw invalidMethod(extractionContext,
                            "the 4th character of the getter method name must be an uppercase character",
                            sampleMethod);
                }

                ModelType<?> returnType = ModelType.returnType(sampleMethod);

                String propertyNameCapitalized = methodName.substring(3);
                String propertyName = StringUtils.uncapitalize(propertyNameCapitalized);
                String setterName = "set" + propertyNameCapitalized;
                ImmutableList<Method> setterMethods = methodsByName.get(setterName);

                boolean isWritable = !setterMethods.isEmpty();
                if (isWritable) {
                    Method setter = setterMethods.get(0);

                    if (!abstractGetter) {
                        throw invalidMethod(extractionContext,
                                "setters are not allowed for non-abstract getters", setter);
                    }
                    validateSetter(extractionContext, returnType, setter);
                    handled.addAll(setterMethods);
                }

                if (abstractGetter) {
                    ImmutableSet<ModelType<?>> declaringClasses = ImmutableSet
                            .copyOf(Iterables.transform(getterMethods, new Function<Method, ModelType<?>>() {
                                public ModelType<?> apply(Method input) {
                                    return ModelType.of(input.getDeclaringClass());
                                }
                            }));

                    boolean unmanaged = Iterables.any(getterMethods, new Predicate<Method>() {
                        public boolean apply(Method input) {
                            return input.getAnnotation(Unmanaged.class) != null;
                        }
                    });

                    properties.add(ModelProperty.of(returnType, propertyName, isWritable, declaringClasses,
                            unmanaged));
                }
                handled.addAll(getterMethods);
            }
        }

        Iterable<Method> notHandled = Iterables.filter(methodsByName.values(),
                Predicates.not(Predicates.in(handled)));

        // TODO - should call out valid getters without setters
        if (!Iterables.isEmpty(notHandled)) {
            throw invalidMethods(extractionContext, "only paired getter/setter methods are supported",
                    notHandled);
        }

        Class<R> concreteClass = type.getConcreteClass();
        Class<? extends R> implClass = classGenerator.generate(concreteClass);
        final ModelStructSchema<R> schema = ModelSchema.struct(type, properties, implClass);
        extractionContext.addValidator(new Action<ModelSchemaExtractionContext<R>>() {
            @Override
            public void execute(ModelSchemaExtractionContext<R> validatorModelSchemaExtractionContext) {
                ensureCanBeInstantiated(extractionContext, schema);
            }
        });
        Iterable<ModelSchemaExtractionContext<?>> propertyDependencies = Iterables.transform(properties,
                new Function<ModelProperty<?>, ModelSchemaExtractionContext<?>>() {
                    public ModelSchemaExtractionContext<?> apply(final ModelProperty<?> property) {
                        return toPropertyExtractionContext(extractionContext, property, cache);
                    }
                });

        return new ModelSchemaExtractionResult<R>(schema, propertyDependencies);
    } else {
        return null;
    }
}

From source file:org.evosuite.setup.TestClusterGenerator.java

protected static void makeAccessible(Method method) {
    if (!Modifier.isPublic(method.getModifiers())
            || !Modifier.isPublic(method.getDeclaringClass().getModifiers())) {
        method.setAccessible(true);//from w ww .j  a v  a  2s .  co  m
    }
}

From source file:de.taimos.dvalin.interconnect.core.spring.InterconnectBeanPostProcessor.java

private InjectionMetadata buildResourceMetadata(Class<?> clazz) {
    LinkedList<InjectionMetadata.InjectedElement> elements = new LinkedList<InjectionMetadata.InjectedElement>();
    Class<?> targetClass = clazz;

    do {//from   w ww  .j  av a2s. co m
        LinkedList<InjectionMetadata.InjectedElement> currElements = new LinkedList<InjectionMetadata.InjectedElement>();
        for (Field field : targetClass.getDeclaredFields()) {
            if (field.isAnnotationPresent(Interconnect.class)) {
                if (Modifier.isStatic(field.getModifiers())) {
                    throw new IllegalStateException(
                            "@Interconnect annotation is not supported on static fields");
                }
                currElements.add(new InterconnectElement(field, null));
            }
        }
        for (Method method : targetClass.getDeclaredMethods()) {
            Method bridgedMethod = BridgeMethodResolver.findBridgedMethod(method);
            if (!BridgeMethodResolver.isVisibilityBridgeMethodPair(method, bridgedMethod)) {
                continue;
            }
            if (method.equals(ClassUtils.getMostSpecificMethod(method, clazz))) {
                if (bridgedMethod.isAnnotationPresent(Interconnect.class)) {
                    if (Modifier.isStatic(method.getModifiers())) {
                        throw new IllegalStateException(
                                "@Interconnect annotation is not supported on static methods");
                    }
                    if (method.getParameterTypes().length != 1) {
                        throw new IllegalStateException(
                                "@Interconnect annotation requires a single-arg method: " + method);
                    }
                    PropertyDescriptor pd = BeanUtils.findPropertyForMethod(bridgedMethod, clazz);
                    currElements.add(new InterconnectElement(method, pd));
                }
            }
        }
        elements.addAll(0, currElements);
        targetClass = targetClass.getSuperclass();
    } while ((targetClass != null) && (targetClass != Object.class));

    return new InjectionMetadata(clazz, elements);
}

From source file:eu.qualityontime.commons.MethodUtils.java

/**
 * <p>/*  ww  w  .  j  av  a  2s  .co m*/
 * Return an accessible method (that is, one that can be invoked via
 * reflection) that implements the specified Method. If no such method can
 * be found, return <code>null</code>.
 * </p>
 *
 * @param clazz
 *            The class of the object
 * @param method
 *            The method that we wish to call
 * @return The accessible method
 * @since 1.8.0
 */
public static Method getAccessibleMethod(Class<?> clazz, Method method) {

    // Make sure we have a method to check
    if (method == null) {
        return null;
    }

    // If the requested method is not public we cannot call it
    if (!Modifier.isPublic(method.getModifiers())) {
        return null;
    }

    boolean sameClass = true;
    if (clazz == null) {
        clazz = method.getDeclaringClass();
    } else {
        sameClass = clazz.equals(method.getDeclaringClass());
        if (!method.getDeclaringClass().isAssignableFrom(clazz)) {
            throw new IllegalArgumentException(
                    clazz.getName() + " is not assignable from " + method.getDeclaringClass().getName());
        }
    }

    // If the class is public, we are done
    if (Modifier.isPublic(clazz.getModifiers())) {
        if (!sameClass && !Modifier.isPublic(method.getDeclaringClass().getModifiers())) {
            setMethodAccessible(method); // Default access superclass
            // workaround
        }
        return method;
    }

    final String methodName = method.getName();
    final Class<?>[] parameterTypes = method.getParameterTypes();

    // Check the implemented interfaces and subinterfaces
    method = getAccessibleMethodFromInterfaceNest(clazz, methodName, parameterTypes);

    // Check the superclass chain
    if (method == null) {
        method = getAccessibleMethodFromSuperclass(clazz, methodName, parameterTypes);
    }

    return method;
}

From source file:org.gradle.model.internal.method.WeaklyTypeReferencingMethod.java

public WeaklyTypeReferencingMethod(ModelType<T> target, ModelType<R> returnType, Method method) {
    this.target = target;
    this.returnType = returnType;
    this.declaringType = ModelType.of(method.getDeclaringClass());
    this.name = method.getName();
    paramTypes = ImmutableList.copyOf(Iterables.transform(Arrays.asList(method.getGenericParameterTypes()),
            new Function<Type, ModelType<?>>() {
                public ModelType<?> apply(Type type) {
                    return ModelType.of(type);
                }//from  www.  j  a va 2 s  . c  o  m
            }));
    modifiers = method.getModifiers();
}

From source file:com.gargoylesoftware.htmlunit.SimpleWebTestCase.java

/**
 * From Junit. Test if the method is a junit test.
 * @param method the method/*from   w  w  w  .  ja  v a2 s .c o  m*/
 * @return <code>true</code> if this is a junit test
 */
private boolean isPublicTestMethod(final Method method) {
    return method.getParameterTypes().length == 0
            && (method.getName().startsWith("test") || method.getAnnotation(Test.class) != null)
            && method.getReturnType() == Void.TYPE && Modifier.isPublic(method.getModifiers());
}

From source file:RssAtomGenerationTest.java

public static <T> T convertObject(final T destination, final Object source, FeedType type, Object... context) {
    Map<Class, Object> contentMap = new HashMap<Class, Object>();
    for (Object o : context) {
        contentMap.put(o.getClass(), o);
    }//from  ww w  . j a  va2  s. c  om
    final Method[] methods = source.getClass().getMethods();
    for (Method method : methods) {
        final boolean refPresent = method.isAnnotationPresent(SyndicationRefs.class);
        if (refPresent || (method.isAnnotationPresent(SyndicationElement.class)
                && method.getAnnotation(SyndicationElement.class).type().equals(type))) {
            SyndicationElement annotation = null;
            if (refPresent) {
                final SyndicationElement[] value = method.getAnnotation(SyndicationRefs.class).value();
                for (SyndicationElement element : value) {
                    if (element.type().equals(type)) {
                        annotation = element;
                        break;
                    }
                }
                if (annotation == null) {
                    continue;
                }
            } else {
                annotation = method.getAnnotation(SyndicationElement.class);
            }
            //final SyndicationElement annotation =
            final String name = annotation.name();
            try {
                final Object initValue = method.invoke(source);
                Object value = null;
                if (!(annotation.converter().isAssignableFrom(NoopConverter.class))) {
                    final Converter converter = annotation.converter().newInstance();
                    value = converter.convert(initValue);
                }
                if (!(annotation.transformer().isAssignableFrom(NoopTransformer.class))) {
                    contentMap.put(initValue.getClass(), initValue);
                    final Class<?> transformer = annotation.transformer();
                    final Method[] transformerMethods = transformer.getMethods();
                    for (Method transformerMethod : transformerMethods) {
                        if (transformerMethod.isAnnotationPresent(ContextTransformable.class)) {
                            final Class<?>[] parameterTypes = transformerMethod.getParameterTypes();
                            List<Object> parameters = new ArrayList<Object>();
                            for (Class clazz : parameterTypes) {
                                if (contentMap.containsKey(clazz)) {
                                    parameters.add(contentMap.get(clazz));
                                } else {
                                    boolean found = false;
                                    for (Object obj : contentMap.values()) {
                                        if (clazz.isInstance(obj)) {
                                            parameters.add(obj);
                                            found = true;
                                            break;
                                        }
                                    }
                                    if (!found) {
                                        parameters.add(null);
                                    }
                                }
                            }
                            if (Modifier.isStatic(transformerMethod.getModifiers())) {
                                value = transformerMethod.invoke(null, parameters.toArray());
                            } else {
                                value = transformerMethod.invoke(transformer.newInstance(),
                                        parameters.toArray());
                            }
                            break;
                        }
                    }

                }
                BeanUtils.setProperty(destination, name, value);
            } catch (Exception e) {
                log.error("test", e);
                e.printStackTrace();
            }

        }
    }
    return destination;
}

From source file:org.eclipse.wb.internal.core.utils.reflect.ReflectionUtils.java

/**
 * Appends components for {@link PropertyDescriptor}'s of given {@link Class}, its super class and
 * implemented interfaces./*from w  w w .j  a  va2  s . c o  m*/
 */
private static void appendPropertyComponents(Class<?> currentClass, Set<String> newPropertyNames,
        Map<String, Method> propertyToGetter, Map<String, Method> propertyToSetter) {
    for (Method method : currentClass.getDeclaredMethods()) {
        int methodModifiers = method.getModifiers();
        boolean isPublic = Modifier.isPublic(methodModifiers);
        boolean isProtected = Modifier.isProtected(methodModifiers);
        boolean isStatic = Modifier.isStatic(methodModifiers);
        if (method.isBridge()) {
            continue;
        }
        if (!isStatic && (isPublic || isProtected)) {
            method.setAccessible(true);
            String methodName = method.getName();
            if (methodName.startsWith("set") && method.getParameterTypes().length == 1) {
                String propertyName = getQualifiedPropertyName(method);
                if (!propertyToSetter.containsKey(propertyName)) {
                    newPropertyNames.add(propertyName);
                    propertyToSetter.put(propertyName, method);
                }
            }
            if (method.getParameterTypes().length == 0) {
                if (methodName.startsWith("get")) {
                    String propertyName = getQualifiedPropertyName(method);
                    if (!propertyToGetter.containsKey(propertyName)) {
                        newPropertyNames.add(propertyName);
                        propertyToGetter.put(propertyName, method);
                    }
                }
                if (methodName.startsWith("is")) {
                    String propertyName = getQualifiedPropertyName(method);
                    if (!propertyToGetter.containsKey(propertyName)) {
                        newPropertyNames.add(propertyName);
                        propertyToGetter.put(propertyName, method);
                    }
                }
            }
        }
    }
    // process interfaces
    for (Class<?> interfaceClass : currentClass.getInterfaces()) {
        appendPropertyComponents(interfaceClass, newPropertyNames, propertyToGetter, propertyToSetter);
    }
    // process super Class
    if (currentClass.getSuperclass() != null) {
        appendPropertyComponents(currentClass.getSuperclass(), newPropertyNames, propertyToGetter,
                propertyToSetter);
    }
}

From source file:de.taimos.dvalin.test.jaxrs.TestProxyBeanPostProcessor.java

private InjectionMetadata buildResourceMetadata(Class<?> clazz) {
    LinkedList<InjectionMetadata.InjectedElement> elements = new LinkedList<InjectionMetadata.InjectedElement>();
    Class<?> targetClass = clazz;

    do {/*w  ww. jav  a2s.  c om*/
        LinkedList<InjectionMetadata.InjectedElement> currElements = new LinkedList<InjectionMetadata.InjectedElement>();
        for (Field field : targetClass.getDeclaredFields()) {
            if (field.isAnnotationPresent(TestProxy.class)) {
                if (Modifier.isStatic(field.getModifiers())) {
                    throw new IllegalStateException("@TestProxy annotation is not supported on static fields");
                }
                currElements.add(new TestProxyElement(field, null));
            }
        }
        for (Method method : targetClass.getDeclaredMethods()) {
            Method bridgedMethod = BridgeMethodResolver.findBridgedMethod(method);
            if (!BridgeMethodResolver.isVisibilityBridgeMethodPair(method, bridgedMethod)) {
                continue;
            }
            if (method.equals(ClassUtils.getMostSpecificMethod(method, clazz))) {
                if (bridgedMethod.isAnnotationPresent(TestProxy.class)) {
                    if (Modifier.isStatic(method.getModifiers())) {
                        throw new IllegalStateException(
                                "@TestProxy annotation is not supported on static methods");
                    }
                    if (method.getParameterTypes().length != 1) {
                        throw new IllegalStateException(
                                "@TestProxy annotation requires a single-arg method: " + method);
                    }
                    PropertyDescriptor pd = BeanUtils.findPropertyForMethod(bridgedMethod, clazz);
                    currElements.add(new TestProxyElement(method, pd));
                }
            }
        }
        elements.addAll(0, currElements);
        targetClass = targetClass.getSuperclass();
    } while ((targetClass != null) && (targetClass != Object.class));

    return new InjectionMetadata(clazz, elements);
}

From source file:org.evosuite.setup.TestClusterGenerator.java

private static boolean hasStaticGenerator(Class<?> clazz) {
    for (Method m : clazz.getMethods()) {
        if (Modifier.isStatic(m.getModifiers())) {
            if (clazz.isAssignableFrom(m.getReturnType())) {
                return true;
            }//from   w  ww.  j  a v a2 s .  c  om
        }
    }
    return false;
}