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:com.espertech.esper.epl.core.EngineImportServiceImpl.java

public Method resolveMethod(String className, String methodName) throws EngineImportException {
    Class clazz;//from   w  w w.  j a va2 s . c  o  m
    try {
        clazz = resolveClassInternal(className, false);
    } catch (ClassNotFoundException e) {
        throw new EngineImportException(
                "Could not load class by name '" + className + "', please check imports", e);
    }

    Method methods[] = clazz.getMethods();
    Method methodByName = null;

    // check each method by name
    for (Method method : methods) {
        if (method.getName().equals(methodName)) {
            if (methodByName != null) {
                throw new EngineImportException("Ambiguous method name: method by name '" + methodName
                        + "' is overloaded in class '" + className + "'");
            }
            int modifiers = method.getModifiers();
            if (Modifier.isPublic(modifiers) && Modifier.isStatic(modifiers)) {
                methodByName = method;
            }
        }
    }

    if (methodByName == null) {
        throw new EngineImportException(
                "Could not find static method named '" + methodName + "' in class '" + className + "'");
    }
    return methodByName;
}

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

/**
 * Gets a list of writable methods / mutator methods. <br>
 * //from w  w  w. java  2  s  .  c  om
 * @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:com.gargoylesoftware.htmlunit.CodeStyleTest.java

private void testTests(final File dir) throws Exception {
    for (final File file : dir.listFiles()) {
        if (file.isDirectory()) {
            if (!".svn".equals(file.getName())) {
                testTests(file);//from ww w  .  jav  a 2s  . co m
            }
        } else {
            if (file.getName().endsWith(".java")) {
                final int index = new File("src/test/java").getAbsolutePath().length();
                String name = file.getAbsolutePath();
                name = name.substring(index + 1, name.length() - 5);
                name = name.replace(File.separatorChar, '.');
                final Class<?> clazz;
                try {
                    clazz = Class.forName(name);
                } catch (final Exception e) {
                    continue;
                }
                name = file.getName();
                if (name.endsWith("Test.java") || name.endsWith("TestCase.java")) {
                    for (final Constructor<?> ctor : clazz.getConstructors()) {
                        if (ctor.getParameterTypes().length == 0) {
                            for (final Method method : clazz.getDeclaredMethods()) {
                                if (Modifier.isPublic(method.getModifiers())
                                        && method.getAnnotation(Before.class) == null
                                        && method.getAnnotation(BeforeClass.class) == null
                                        && method.getAnnotation(After.class) == null
                                        && method.getAnnotation(AfterClass.class) == null
                                        && method.getAnnotation(Test.class) == null
                                        && method.getReturnType() == Void.TYPE
                                        && method.getParameterTypes().length == 0) {
                                    fail("Method '" + method.getName() + "' in " + name
                                            + " does not declare @Test annotation");
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}

From source file:net.camelpe.extension.camel.typeconverter.CdiTypeConverterBuilder.java

private void ensureConverterMethodIsValid(final Class<?> type, final Method method)
        throws IllegalArgumentException {
    final Class<?>[] parameterTypes = method.getParameterTypes();
    final boolean hasCorrectParameters = (parameterTypes != null) && ((parameterTypes.length == 1)
            || ((parameterTypes.length == 2) && Exchange.class.isAssignableFrom(parameterTypes[1])));
    if (!hasCorrectParameters) {
        throw new IllegalArgumentException("Illegal converter method [" + method + "] on type ["
                + type.getName()/*from w  w  w.ja  v  a 2 s . c  o m*/
                + "]: a converter method must have exactly one parameter, or it must have exactly "
                + "two parameters where the second parameter is of type [" + Exchange.class.getName() + "].");
    }

    final int modifiers = method.getModifiers();
    if (isAbstract(modifiers) || !isPublic(modifiers)) {
        throw new IllegalArgumentException("Illegal converter method [" + method + "] on type ["
                + type.getName() + "]: a converter method must not be abstract, and it must be public.");
    }

    final Class<?> toType = method.getReturnType();
    if (toType.equals(Void.class)) {
        throw new IllegalArgumentException("Illegal converter method [" + method + "] on type ["
                + type.getName() + "]: a converter method must not return void.");
    }
}

From source file:com.gatf.executor.core.AcceptanceTestContext.java

@SuppressWarnings("rawtypes")
public Class addTestCaseHooks(Method method) {
    Class claz = null;//w w w. j  a va  2s .c o m
    if (method != null && Modifier.isStatic(method.getModifiers())) {

        Annotation preHook = method.getAnnotation(PreTestCaseExecutionHook.class);
        Annotation postHook = method.getAnnotation(PostTestCaseExecutionHook.class);

        if (preHook != null) {
            PreTestCaseExecutionHook hook = (PreTestCaseExecutionHook) preHook;

            if (method.getParameterTypes().length != 1
                    || !method.getParameterTypes()[0].equals(TestCase.class)) {
                logger.severe("PreTestCaseExecutionHook annotated methods should "
                        + "confirm to the method signature - `public static void {methodName} ("
                        + "TestCase testCase)`");
                return claz;
            }

            if (hook.value() != null && hook.value().length > 0) {
                for (String testCaseName : hook.value()) {
                    if (testCaseName != null && !testCaseName.trim().isEmpty()) {
                        prePostTestCaseExecHooks.put("pre" + testCaseName, method);
                    }
                }
            } else {
                prePostTestCaseExecHooks.put("preAll", method);
            }
            claz = method.getDeclaringClass();
        }
        if (postHook != null) {
            PostTestCaseExecutionHook hook = (PostTestCaseExecutionHook) postHook;

            if (method.getParameterTypes().length != 1
                    || !method.getParameterTypes()[0].equals(TestCaseReport.class)) {
                logger.severe("PostTestCaseExecutionHook annotated methods should "
                        + "confirm to the method signature - `public static void {methodName} ("
                        + "TestCaseReport testCaseReport)`");
                return claz;
            }

            if (hook.value() != null && hook.value().length > 0) {
                for (String testCaseName : hook.value()) {
                    if (testCaseName != null && !testCaseName.trim().isEmpty()) {
                        prePostTestCaseExecHooks.put("post" + testCaseName, method);
                    }
                }
            } else {
                prePostTestCaseExecHooks.put("postAll", method);
            }
            claz = method.getDeclaringClass();
        }
    }
    return claz;
}

From source file:com.mycila.plugin.Cglib2AopProxy.java

/**
 * Checks for final methods on the <code>Class</code> and writes warnings to the log
 * for each one found./*  w  w  w .j a  va2  s . c om*/
 */
private void doValidateClass(Class proxySuperClass) {
    Method[] methods = proxySuperClass.getMethods();
    for (Method method : methods) {
        if (!Object.class.equals(method.getDeclaringClass()) && Modifier.isFinal(method.getModifiers())) {
            logger.warn("Unable to proxy method [" + method + "] because it is final: "
                    + "All calls to this method via a proxy will be routed directly to the proxy.");
        }
    }
}

From source file:com.javaforge.tapestry.acegi.enhance.SecuredMethodEnhancementWorker.java

@SuppressWarnings("unused")
public void performEnhancement(EnhancementOperation op, IComponentSpecification spec, Method method,
        Location location) {//from  w  w w  .ja  v  a 2s .  c o  m
    getLog().debug("Securing method " + method + "...");
    final String securityUtilsField = op.addInjectedField("_$securityUtils", SecurityUtils.class,
            securityUtils);
    final Collection<ConfigAttribute> configAttributeDefinition = securityUtils
            .createConfigAttributeDefinition(method);
    final String configAttributeDefinitionField = op.addInjectedField("_$configAttributeDefinition",
            Collection.class, configAttributeDefinition);
    final StringBuffer methodBody = new StringBuffer("{\n");
    methodBody.append(securityUtilsField + ".checkSecurity(this," + configAttributeDefinitionField + ");\n");
    if (!method.getReturnType().equals(Void.TYPE)) {
        methodBody.append("return ");
    }
    methodBody.append("super." + method.getName() + "($$);\n}");
    op.addMethod(method.getModifiers(), new MethodSignature(method), methodBody.toString(), location);
}

From source file:org.apache.dubbo.config.spring.beans.factory.annotation.CompatibleReferenceAnnotationBeanPostProcessor.java

/**
 * Finds {@link InjectionMetadata.InjectedElement} Metadata from annotated {@link Reference @Reference} methods
 *
 * @param beanClass The {@link Class} of Bean
 * @return non-null {@link List}//  w w  w .  j a  v a 2 s  .  c om
 */
private List<ReferenceMethodElement> findMethodReferenceMetadata(final Class<?> beanClass) {

    final List<ReferenceMethodElement> elements = new LinkedList<ReferenceMethodElement>();

    ReflectionUtils.doWithMethods(beanClass, new ReflectionUtils.MethodCallback() {
        @Override
        public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {

            Method bridgedMethod = findBridgedMethod(method);

            if (!isVisibilityBridgeMethodPair(method, bridgedMethod)) {
                return;
            }

            Reference reference = findAnnotation(bridgedMethod, Reference.class);

            if (reference != null && method.equals(ClassUtils.getMostSpecificMethod(method, beanClass))) {
                if (Modifier.isStatic(method.getModifiers())) {
                    if (logger.isWarnEnabled()) {
                        logger.warn("@Reference annotation is not supported on static methods: " + method);
                    }
                    return;
                }
                if (method.getParameterTypes().length == 0) {
                    if (logger.isWarnEnabled()) {
                        logger.warn("@Reference  annotation should only be used on methods with parameters: "
                                + method);
                    }
                }
                PropertyDescriptor pd = BeanUtils.findPropertyForMethod(bridgedMethod, beanClass);
                elements.add(new ReferenceMethodElement(method, pd, reference));
            }
        }
    });

    return elements;

}