Example usage for java.lang.reflect Method isAnnotationPresent

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

Introduction

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

Prototype

@Override
public boolean isAnnotationPresent(Class<? extends Annotation> annotationClass) 

Source Link

Usage

From source file:support.RightSeeker.java

public RightStack createSpringRightsFromJar(Class startclass, String prefix) throws Exception {
    mapping = new HashMap();
    RightStack result = RightStack.getInstance(prefix);
    Collection string = JarScan.scanClasses(JarScan.getFilePathToClasses(startclass));

    for (Object cls : string) {
        Class cl = Class.forName(cls.toString());

        if (cl.isAnnotationPresent(org.springframework.stereotype.Controller.class)) {
            Object obj = cl.newInstance();
            Method[] methods = obj.getClass().getDeclaredMethods();
            for (Method method : methods) {
                String mappingName = "";
                if (cl.isAnnotationPresent(RequestMapping.class)) {
                    RequestMapping rm = (RequestMapping) cl.getAnnotation(RequestMapping.class);
                    if (rm.value().length > 0) {
                        mappingName = rm.value()[0];
                    }//from w  ww  .  j  av  a2s  . co m
                }
                if (method.isAnnotationPresent(support.commons.Right.class)) {
                    support.commons.Right methAnn = method.getAnnotation(support.commons.Right.class);
                    if (method.isAnnotationPresent(RequestMapping.class)) {
                        RequestMapping rmmethod = method.getAnnotation(RequestMapping.class);
                        if (rmmethod.value().length > 0) {
                            mappingName += rmmethod.value()[0];
                        }

                    }

                    String action = method.getName();
                    if (StringAdapter.NotNull(methAnn.name())) {
                        action = methAnn.name();
                    }
                    Right rt = result.add(cl.getName(), action, cl.getName(), methAnn.description());
                    if (StringAdapter.NotNull(mappingName)) {
                        mapping.put(mappingName, rt);
                    }
                }
            }

        }
    }
    return result;
}

From source file:org.microtitan.diffusive.launcher.DiffusiveLoader.java

/**
 * Invokes the methods of the classes specified in the {@link #configurationClasses} list
 * that are annotated with @{@link DiffusiveConfiguration}.
 * /*  w ww . j a  v a2  s.  co m*/
 * For this method to work, the @{@link DiffusiveConfiguration} class name must be in the list
 * of prefixes ({@link #delegationPrefixes}) that are delegated to the parent class loader. If
 * the annotation does not appear in the list, it may be loaded by this class loader instead
 * of the default app class loader, and this method will not see the configuration method's
 * annotation, and will therefore, NOT call it.
 *  
 * @throws Throwable
 */
private void invokeConfigurationClasses() throws Throwable {
    // run through the class names, load the classes, and then invoke the configuration methods
    // (that have been annotated with @DiffusiveConfiguration)
    for (Map.Entry<String, Object[]> className : configurationClasses.entrySet()) {
        final Class<?> setupClazz = loadClass(className.getKey());
        Method configurationMethod = null;
        try {
            // grab the methods that have an annotation @DiffusiveConfiguration and invoke them
            for (final Method method : setupClazz.getMethods()) {
                if (method.isAnnotationPresent(DiffusiveConfiguration.class)) {
                    // hold on the the method in case there is an invocation exception
                    // and to warn the user if no configuration method was found
                    configurationMethod = method;
                    method.invoke(null, className.getValue());
                }
            }
            if (configurationMethod == null) {
                final StringBuilder message = new StringBuilder();
                message.append("Error finding a method annotated with @")
                        .append(DiffusiveConfiguration.class.getSimpleName()).append(Constants.NEW_LINE)
                        .append("  Configuration Class: ").append(className).append(Constants.NEW_LINE);
                LOGGER.warn(message.toString());
            }
        } catch (InvocationTargetException e) {
            final StringBuilder message = new StringBuilder();
            message.append("Error invoking target method.").append(Constants.NEW_LINE).append("  Class Name: ")
                    .append(className).append(Constants.NEW_LINE).append("  Method Name: ")
                    .append(configurationMethod.getName());
            LOGGER.error(message.toString(), e);
            throw new IllegalArgumentException(message.toString(), e);
        }
    }
}

From source file:com.laxser.blitz.web.impl.module.ControllerRef.java

private boolean quicklyPass(List<Method> pastMethods, Method method, Class<?> controllerClass) {
    // public, not static, not abstract, @Ignored
    if (!Modifier.isPublic(method.getModifiers()) || Modifier.isAbstract(method.getModifiers())
            || Modifier.isStatic(method.getModifiers()) || method.isAnnotationPresent(Ignored.class)) {
        if (logger.isDebugEnabled()) {
            logger.debug("ignores method of controller " + controllerClass.getName() + "." + method.getName()
                    + "  [@ignored?not public?abstract?static?]");
        }/*  w w w  . j  a va  2s  . co  m*/
        return true;
    }
    // ?(?)?????
    for (Method past : pastMethods) {
        if (past.getName().equals(method.getName())) {
            if (Arrays.equals(past.getParameterTypes(), method.getParameterTypes())) {
                return true;
            }
        }
    }
    return false;
}

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

@SuppressWarnings("unchecked")
@Override/*  w  w w. j  a va 2s . co  m*/
public void saveSettings(Settings instance, String fn, String comment) {
    Class<?> clazz = instance.getClass().getInterfaces()[0];
    Class<?> invocableClazz = instance.getClass();
    //      File file = new File("/" + DIR_PATH + "/" + fn);
    File file = new File(fn);
    Properties props = new SortedProperties();

    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];

                try {
                    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)) {
                                    List<InetSocketAddress> isaArr = (List<InetSocketAddress>) invocableClazz
                                            .getMethod("get" + method.getName().substring(3)).invoke(instance);
                                    int cnt = isaArr.size();
                                    props.setProperty(param.name() + ".count", String.valueOf(cnt));
                                    for (int i = 0; i < cnt; ++i) {
                                        props.setProperty(param.name() + "." + String.valueOf(i) + ".ip",
                                                isaArr.get(i).getHostString());
                                        props.setProperty(param.name() + "." + String.valueOf(i) + ".port",
                                                String.valueOf(isaArr.get(i).getPort()));
                                    }
                                } else {
                                    throw new RuntimeException("Settings param in class "
                                            + clazz.getCanonicalName() + " with method " + method.getName()
                                            + " not implemented yet");
                                }
                            }

                        }
                    } else if (paramClazz.isPrimitive()) {
                        props.setProperty(param.name(), String.valueOf(invocableClazz
                                .getMethod("get" + method.getName().substring(3)).invoke(instance)));
                    } else if (String.class.isAssignableFrom(paramClazz)) {
                        props.setProperty(param.name(), (String) (invocableClazz
                                .getMethod("get" + method.getName().substring(3)).invoke(instance)));
                    } else {
                        throw new RuntimeException("Settings param in class " + clazz.getCanonicalName()
                                + " with method " + method.getName() + " not implemented yet");
                    }
                    BotUtils.saveProperties(file, props, "Bot v" + VERSION);
                } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException
                        | NoSuchMethodException | IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

From source file:org.ff4j.aop.FeatureAdvisor.java

/** {@inheritDoc} */
@Override/*from w ww  . j a v  a  2 s  .c  o m*/
public Object invoke(final MethodInvocation pMInvoc) throws Throwable {
    Method method = pMInvoc.getMethod();
    Logger targetLogger = getLogger(method);
    Flip ff = null;
    if (method.isAnnotationPresent(Flip.class)) {
        ff = method.getAnnotation(Flip.class);
    } else if (method.getDeclaringClass().isAnnotationPresent(Flip.class)) {
        ff = method.getDeclaringClass().getAnnotation(Flip.class);
    }

    if (ff != null) {
        FlippingExecutionContext context = retrieveContext(ff, pMInvoc, targetLogger);
        if (shouldFlip(ff, context)) {

            // Required parameters
            if (!assertRequiredParams(ff)) {
                String msg = String.format("alterBeanName or alterClazz is required for {%s}",
                        method.getDeclaringClass());
                throw new IllegalArgumentException(msg);
            }
            if (shouldCallAlterBeanMethod(pMInvoc, ff.alterBean(), targetLogger)) {
                return callAlterBeanMethod(pMInvoc, ff.alterBean(), targetLogger);
            }
            // Test alterClazz Property of annotation
            if (shouldCallAlterClazzMethod(pMInvoc, ff.alterClazz(), targetLogger)) {
                return callAlterClazzMethodOnFirst(pMInvoc, ff, targetLogger);
            }
        }
    }
    // do not catch throwable
    return pMInvoc.proceed();
}

From source file:org.springframework.test.context.junit4.SpringJUnit4ClassRunner.java

/**
 * Return {@code true} if {@link Ignore @Ignore} is present for the supplied
 * {@linkplain FrameworkMethod test method} or if the test method is disabled
 * via {@code @IfProfileValue}.//from w  w  w.j  a  va 2  s  . c  om
 * @see ProfileValueUtils#isTestEnabledInThisEnvironment(Method, Class)
 */
protected boolean isTestMethodIgnored(FrameworkMethod frameworkMethod) {
    Method method = frameworkMethod.getMethod();
    return (method.isAnnotationPresent(Ignore.class)
            || !ProfileValueUtils.isTestEnabledInThisEnvironment(method, getTestClass().getJavaClass()));
}

From source file:org.eclipse.smila.management.jmx.AgentMBean.java

/**
 * Process value./*ww w  .j  a v a 2  s .c om*/
 * 
 * @param result
 *          the result
 * @param method
 *          the method
 * 
 * @return the object
 */
private Object processValue(final Object result, final Method method) {
    if (result == null) {
        return null;
    }
    if (PerformanceCounter.class.isAssignableFrom(result.getClass())) {
        final PerformanceCounter counter = (PerformanceCounter) result;
        double value = counter.getNextSampleValue();
        if (method.isAnnotationPresent(Coefficient.class)) {
            final Coefficient coefficient = method.getAnnotation(Coefficient.class);
            final double coefficientToApply = coefficient.value();
            value = value * coefficientToApply;
        }
        return value;
    }
    if (ErrorsBuffer.class.isAssignableFrom(result.getClass())) {
        final ErrorsBuffer buffer = (ErrorsBuffer) result;
        return buffer.getErrors();
    }
    return result;
}

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   ww  w  .j a  v a 2  s .  c  om
        //         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: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 {// w ww .ja  va 2  s . 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:com.haulmont.cuba.core.sys.MetadataImpl.java

protected void invokePostConstructMethods(Entity entity)
        throws InvocationTargetException, IllegalAccessException {
    List<Method> postConstructMethods = new ArrayList<>(4);
    List<String> methodNames = new ArrayList<>(4);
    Class clazz = entity.getClass();
    while (clazz != Object.class) {
        Method[] classMethods = clazz.getDeclaredMethods();
        for (Method method : classMethods) {
            if (method.isAnnotationPresent(PostConstruct.class) && !methodNames.contains(method.getName())) {
                postConstructMethods.add(method);
                methodNames.add(method.getName());
            }//from w ww .  ja  v  a 2  s. c  o  m
        }
        clazz = clazz.getSuperclass();
    }

    ListIterator<Method> iterator = postConstructMethods.listIterator(postConstructMethods.size());
    while (iterator.hasPrevious()) {
        Method method = iterator.previous();
        if (!method.isAccessible()) {
            method.setAccessible(true);
        }
        method.invoke(entity);
    }
}