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:com.are.photophone.utils.permissionutils.EasyPermissions.java

private static void runAnnotatedMethods(Object object, int requestCode) {
    Class clazz = object.getClass();
    if (isUsingAndroidAnnotations(object)) {
        clazz = clazz.getSuperclass();/*from   w w w .  j  a va2s .c om*/
    }
    for (Method method : clazz.getDeclaredMethods()) {
        if (method.isAnnotationPresent(AfterPermissionGranted.class)) {
            // Check for annotated methods with matching request code.
            AfterPermissionGranted ann = method.getAnnotation(AfterPermissionGranted.class);
            if (ann.value() == requestCode) {
                // Method must be void so that we can invoke it
                if (method.getParameterTypes().length > 0) {
                    throw new RuntimeException("Cannot execute non-void method " + method.getName());
                }

                try {
                    // Make method accessible if private
                    if (!method.isAccessible()) {
                        method.setAccessible(true);
                    }
                    method.invoke(object);
                } catch (IllegalAccessException e) {
                    Log.e(TAG, "runDefaultMethod:IllegalAccessException", e);
                } catch (InvocationTargetException e) {
                    Log.e(TAG, "runDefaultMethod:InvocationTargetException", e);
                }
            }
        }
    }
}

From source file:la.xiong.mylibrary.EasyPermissions.java

/**
 * Find all methods annotated with {@link } on a given object with the
 * correc requestCode argument./*from  w w w.  j  a va 2s. com*/
 * @param object the object with annotated methods.
 * @param requestCode the requestCode passed to the annotation.
 */
private static void runAnnotatedMethods(@NonNull Object object, int requestCode) {
    Class clazz = object.getClass();
    if (isUsingAndroidAnnotations(object)) {
        clazz = clazz.getSuperclass();
    }

    while (clazz != null) {
        for (Method method : clazz.getDeclaredMethods()) {
            if (method.isAnnotationPresent(AfterPermissionGranted.class)) {
                // Check for annotated methods with matching request code.
                AfterPermissionGranted ann = method.getAnnotation(AfterPermissionGranted.class);
                if (ann.value() == requestCode) {
                    // Method must be void so that we can invoke it
                    if (method.getParameterTypes().length > 0) {
                        throw new RuntimeException("Cannot execute method " + method.getName()
                                + " because it is non-void method and/or has input parameters.");
                    }

                    try {
                        // Make method accessible if private
                        if (!method.isAccessible()) {
                            method.setAccessible(true);
                        }
                        method.invoke(object);
                    } catch (IllegalAccessException e) {
                        Log.e(TAG, "runDefaultMethod:IllegalAccessException", e);
                    } catch (InvocationTargetException e) {
                        Log.e(TAG, "runDefaultMethod:InvocationTargetException", e);
                    }
                }
            }
        }

        clazz = clazz.getSuperclass();
    }
}

From source file:xiaofei.library.hermes.util.TypeUtils.java

public static void validateAccessible(Method method) throws HermesException {
    if (method.isAnnotationPresent(WithinProcess.class)) {
        throw new HermesException(ErrorCodes.METHOD_WITH_PROCESS,
                "Method " + method.getName() + " of class " + method.getDeclaringClass().getName()
                        + " has a WithProcess annotation on it, so it cannot be accessed from "
                        + "outside the process.");
    }//from w  w  w .j a  v a2  s  .c  o  m
}

From source file:dk.netdesign.common.osgi.config.Attribute.java

private static String getAttributeName(Method classMethod) {
    String attributeName = classMethod.getName().replaceAll("^get", "");
    if (classMethod.isAnnotationPresent(Property.class)) {
        Property methodProperty = classMethod.getAnnotation(Property.class);
        if (!methodProperty.name().isEmpty()) {
            attributeName = methodProperty.name();
        }//from  w  ww  . j  a v a2s  . c  om
    }
    return attributeName;
}

From source file:com.reactivetechnologies.platform.rest.WebbitRestServerBean.java

/**
 * //from w w  w .  jav  a  2s.  co  m
 * @param restletClass
 * @return
 * @throws InstantiationException
 * @throws IllegalAccessException
 */
static JAXRSInstanceMetadata scanJaxRsClass(Class<?> restletClass)
        throws InstantiationException, IllegalAccessException {
    final JAXRSInstanceMetadata proxy = new JAXRSInstanceMetadata(restletClass.newInstance());
    if (restletClass.isAnnotationPresent(Path.class)) {
        String rootUri = restletClass.getAnnotation(Path.class).value();
        if (rootUri == null)
            rootUri = "";
        proxy.setRootUri(rootUri);
    }
    ReflectionUtils.doWithMethods(restletClass, new MethodCallback() {

        @Override
        public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
            String subUri = "";
            if (method.isAnnotationPresent(Path.class)) {
                subUri = method.getAnnotation(Path.class).value();
            }
            if (method.isAnnotationPresent(GET.class)) {
                MethodDetail m = createMethodDetail(method);
                proxy.addGetMethod(proxy.getRootUri() + subUri, m);
            }
            if (method.isAnnotationPresent(POST.class)) {
                MethodDetail m = createMethodDetail(method);
                proxy.addPostMethod(proxy.getRootUri() + subUri, m);
            }
            if (method.isAnnotationPresent(DELETE.class)) {
                MethodDetail m = createMethodDetail(method);
                proxy.addDelMethod(proxy.getRootUri() + subUri, m);
            }

        }
    }, new MethodFilter() {

        @Override
        public boolean matches(Method method) {
            return (method.isAnnotationPresent(GET.class) || method.isAnnotationPresent(POST.class)
                    || method.isAnnotationPresent(DELETE.class));
        }
    });

    return proxy;
}

From source file:org.jboss.errai.ioc.util.CDIAnnotationUtils.java

/**
 * <p>Generate a hash code for the given annotation using the algorithm
 * presented in the {@link Annotation#hashCode()} API docs.</p>
 *
 * @param a the Annotation for a hash code calculation is desired, not
 * {@code null}/*from   www  .java  2 s  .  c o m*/
 * @return the calculated hash code
 * @throws RuntimeException if an {@code Exception} is encountered during
 * annotation member access
 * @throws IllegalStateException if an annotation method invocation returns
 * {@code null}
 */
public static int hashCode(Annotation a) {
    int result = 0;
    Class<? extends Annotation> type = a.annotationType();
    for (Method m : type.getDeclaredMethods()) {
        if (!m.isAnnotationPresent(Nonbinding.class)) {
            try {
                Object value = m.invoke(a);
                if (value == null) {
                    throw new IllegalStateException(String.format("Annotation method %s returned null", m));
                }
                result += hashMember(m.getName(), value);
            } catch (RuntimeException ex) {
                throw ex;
            } catch (Exception ex) {
                throw new RuntimeException(ex);
            }
        }
    }
    return result;
}

From source file:org.lightjason.agentspeak.common.CCommon.java

/**
 * class filter of an action to use it/*from   w w  w .ja  v a 2s. c o m*/
 *
 * @param p_method method for checking
 * @param p_root root class
 * @return boolean flag of check result
 */
private static boolean isActionFiltered(final Method p_method, final Class<?> p_root) {
    return p_method.isAnnotationPresent(IAgentActionFilter.class)
            && ((p_method.getAnnotation(IAgentActionFilter.class).classes().length == 0)
                    || (Arrays.stream(p_method.getAnnotation(IAgentActionFilter.class).classes()).parallel()
                            .anyMatch(p_root::equals)));
}

From source file:dk.netdesign.common.osgi.config.Attribute.java

private static Class getMethodReturnType(Method classMethod) throws InvalidMethodException {
    Class methodReturnType = classMethod.getReturnType();
    if (classMethod.isAnnotationPresent(Property.class)) {
        Property methodProperty = classMethod.getAnnotation(Property.class);
        if (List.class.isAssignableFrom(methodReturnType) && methodProperty.type() == void.class) {
            throw new InvalidMethodException("Could not create handler for method " + classMethod.getName()
                    + ". Lists must be accompanied by a returnType");
        }//from   w w w .  j a  v a  2 s . c  o  m
    }
    return methodReturnType;
}

From source file:com.github.cherimojava.data.mongo.entity.EntityUtils.java

/**
 * retrieves the name of the property which is used on mongodb side. Accepts only get methods, will throw an
 * exception for all other methods//w w  w. j a  v a  2  s  .  c om
 *
 * @param m method to retrieve mongo name from
 * @return mongo name for the given getter method (parameter)
 */
static String getMongoNameFromMethod(Method m) {
    checkArgument(m.getName().startsWith("get") || m.getName().startsWith("is"),
            "Mongo name can only be retrieved from get/is methods, but was %s", m.getName());
    checkArgument(!(m.isAnnotationPresent(Named.class) && m.isAnnotationPresent(Id.class)),
            "You can not annotate a property with @Name and @Id");
    if (m.isAnnotationPresent(Named.class)) {
        checkArgument(!Entity.ID.equals(m.getAnnotation(Named.class).value()),
                "It's not allowed to use @Name annotation to declare id field, instead use @Id annotation");
        return m.getAnnotation(Named.class).value();
    }
    if (m.isAnnotationPresent(Id.class) || "id".equals(getPojoNameFromMethod(m).toLowerCase(Locale.US))) {
        return Entity.ID;
    }
    // differentiate between get and is methods
    return decapitalize(m.getName().substring(m.getName().startsWith("get") ? 3 : 2));
}

From source file:org.jspare.forvertx.web.collector.HandlerCollector.java

private static List<org.jspare.forvertx.web.handler.BodyEndHandler> collectBodyEndHandlers(
        Transporter transporter, Method method) {

    List<org.jspare.forvertx.web.handler.BodyEndHandler> handlers = new ArrayList<>();
    handlers.addAll(Optional.ofNullable(transporter.getDefaultBodyEndHandlers()).orElse(Arrays.asList()));
    if (method.isAnnotationPresent(BodyEndHandler.class)) {

        Arrays.asList(method.getAnnotation(BodyEndHandler.class).value()).forEach(c -> {
            try {
                handlers.add(c.newInstance());
            } catch (InstantiationException | IllegalAccessException e) {

                log.error("Cannot add bodyEndHandler [{}] to route instead of [{}]", c.getName(),
                        method.getName());
            }/*from   w  ww.  jav a2 s. c  o m*/
        });
    }
    return handlers;
}