Example usage for java.lang.reflect Method getAnnotation

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

Introduction

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

Prototype

public <T extends Annotation> T getAnnotation(Class<T> annotationClass) 

Source Link

Usage

From source file:ca.uhn.fhir.rest.method.HistoryMethodBinding.java

private static Class<? extends IBaseResource> toReturnType(Method theMethod, Object theProvider) {
    if (theProvider instanceof IResourceProvider) {
        return ((IResourceProvider) theProvider).getResourceType();
    }//from   w ww.  j  a va2 s .com
    History historyAnnotation = theMethod.getAnnotation(History.class);
    Class<? extends IResource> type = historyAnnotation.type();
    if (type != IResource.class) {
        return type;
    }
    return null;
}

From source file:bdi4jade.util.ReflectionUtils.java

private static void setupParameters(Object obj1, Direction[] dir1, Object obj2, Direction[] dir2)
        throws ParameterException {
    for (Method method : obj1.getClass().getMethods()) {
        if (method.isAnnotationPresent(Parameter.class)) {
            Parameter parameter = method.getAnnotation(Parameter.class);

            if (!isParameterIn(parameter, dir1)) {
                continue;
            }//from   w  w  w .  j a v  a  2s .c  o  m

            if (!(isGetter(method) || isSetter(method))) {
                checkSkipIsOK(parameter, "Method " + method + " should be a getter or setter.", null);
                continue;
            }

            String property = null;
            Method setter = null;

            if (isGetter(method)) {
                property = methodToPropertyName(GETTER_PREFIX, method);
                try {
                    setter = obj1.getClass().getMethod(propertyToMethodName(SETTER_PREFIX, property),
                            method.getReturnType());
                } catch (NoSuchMethodException nsme) {
                    checkSkipIsOK(parameter, "There is no setter method associated with property " + property,
                            nsme);
                    continue;
                }
            } else {
                property = methodToPropertyName(SETTER_PREFIX, method);
                setter = method;
            }

            Method getter = null;
            try {
                getter = obj2.getClass().getMethod(propertyToMethodName(GETTER_PREFIX, property));
                if (!getter.isAnnotationPresent(Parameter.class)
                        || !isParameterIn(getter.getAnnotation(Parameter.class), dir2)) {
                    checkSkipIsOK(parameter,
                            "There is no parameter associated with method " + method + " name " + property,
                            null);
                    continue;
                }
            } catch (NoSuchMethodException nsme) {
                checkSkipIsOK(parameter, "There is no getter method associated with property " + property,
                        nsme);
                continue;
            }

            try {
                setter.invoke(obj1, getter.invoke(obj2));
            } catch (Exception exc) {
                checkSkipIsOK(parameter, "An unknown error occurrred.", exc);
            }
        }
    }
}

From source file:com.googlecode.jsonplugin.JSONUtil.java

/**
 * List visible methods carrying the @SMDMethod annotation
 *
 * @param ignoreInterfaces if true, only the methods of the class are examined.  If false, annotations on
 *                         every interfaces' methods are examined.
 *//*from   w  ww .j  a  v a  2s.c  o  m*/
@SuppressWarnings("unchecked")
public static Method[] listSMDMethods(Class clazz, boolean ignoreInterfaces) {
    final List<Method> methods = new LinkedList<Method>();
    if (ignoreInterfaces) {
        for (Method method : clazz.getMethods()) {
            SMDMethod smdMethodAnnotation = method.getAnnotation(SMDMethod.class);
            if (smdMethodAnnotation != null) {
                methods.add(method);
            }
        }
    } else {
        // recurse the entire superclass/interface hierarchy and add in order encountered
        JSONUtil.visitInterfaces(clazz, new JSONUtil.ClassVisitor() {
            public boolean visit(Class aClass) {
                for (Method method : aClass.getMethods()) {
                    SMDMethod smdMethodAnnotation = method.getAnnotation(SMDMethod.class);
                    if (smdMethodAnnotation != null && !methods.contains(method)) {
                        methods.add(method);
                    }
                }
                return true;
            }
        });
    }

    Method[] methodResult = new Method[methods.size()];
    return methods.toArray(methodResult);
}

From source file:com.haulmont.cuba.core.config.ConfigUtil.java

/**
 * Get the default value of a configuration interface method. If a
 * {@link Default} annotation is present then that string is converted
 * to the appropriate type using the {@link TypeFactory} class.
 * Otherwise, for the type Foo, this searches for a FooDefault
 * annotation. If such an annotation is present then its value is
 * returned.//from ww w .j a v a 2s .c  o  m
 *
 * @param configInterface The configuration interface.
 * @param method          The method.
 * @return The default value, or null.
 */
public static String getDefaultValue(Class<?> configInterface, Method method) {
    // TODO: returnType.cast()?
    try {
        Default defaultValue = method.getAnnotation(Default.class);
        if (defaultValue != null) {
            return defaultValue.value();
        } else {
            Class<?> type = method.getReturnType();
            if (EnumClass.class.isAssignableFrom(type)) {
                @SuppressWarnings("unchecked")
                Class<EnumClass> enumeration = (Class<EnumClass>) type;
                EnumStore mode = getAnnotation(configInterface, method, EnumStore.class, true);
                if (mode != null && EnumStoreMode.ID == mode.value()) {
                    Class<?> idType = getEnumIdType(enumeration);
                    String name = "Default" + StringUtils.capitalize(ClassUtils.getShortClassName(idType));
                    Object value = getAnnotationValue(method, name);
                    if (value != null) {
                        Method fromId = enumeration.getDeclaredMethod("fromId", idType);
                        TypeStringify stringConverter = TypeStringify.getInstance(configInterface, method);
                        return stringConverter.stringify(fromId.invoke(null, value));
                    }
                    return NO_DEFAULT;
                }
            }
            String name = "Default" + StringUtils.capitalize(ClassUtils.getShortClassName(type));
            Object value = getAnnotationValue(method, name);
            if (value != null) {
                TypeStringify stringConverter = TypeStringify.getInstance(configInterface, method);
                return stringConverter.stringify(value);
            }
        }
        return NO_DEFAULT;
    } catch (Exception ex) {
        throw new RuntimeException("Default value error", ex);
    }
}

From source file:com.hurence.logisland.util.kura.Metrics.java

public static <T> T readFrom(final T object, final Map<String, Object> metrics) {
    Objects.requireNonNull(object);

    for (final Field field : FieldUtils.getFieldsListWithAnnotation(object.getClass(), Metric.class)) {
        final Metric m = field.getAnnotation(Metric.class);
        final boolean optional = field.isAnnotationPresent(Optional.class);

        final Object value = metrics.get(m.value());
        if (value == null && !optional) {
            throw new IllegalArgumentException(
                    String.format("Field '%s' is missing metric '%s'", field.getName(), m.value()));
        }/*from w  w w. java  2s. co m*/

        if (value == null) {
            // not set but optional
            continue;
        }

        try {
            FieldUtils.writeField(field, object, value, true);
        } catch (final IllegalArgumentException e) {
            // provide a better message
            throw new IllegalArgumentException(String.format("Failed to assign '%s' (%s) to field '%s'", value,
                    value.getClass().getName(), field.getName()), e);
        } catch (final IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

    for (final Method method : MethodUtils.getMethodsListWithAnnotation(object.getClass(), Metric.class)) {
        final Metric m = method.getAnnotation(Metric.class);
        final boolean optional = method.isAnnotationPresent(Optional.class);

        final Object value = metrics.get(m.value());
        if (value == null && !optional) {
            throw new IllegalArgumentException(
                    String.format("Method '%s' is missing metric '%s'", method.getName(), m.value()));
        }

        if (value == null) {
            // not set but optional
            continue;
        }

        try {
            method.invoke(object, value);
        } catch (final IllegalArgumentException e) {
            // provide a better message
            throw new IllegalArgumentException(String.format("Failed to call '%s' (%s) with method '%s'", value,
                    value.getClass().getName(), method.getName()), e);
        } catch (IllegalAccessException | InvocationTargetException e) {
            throw new RuntimeException(e);
        }
    }

    return object;
}

From source file:com.startechup.tools.ModelParser.java

/**
 * Gets the values from the {@link JSONObject JSONObjects}/response returned from an api call
 * request and assign it to the field inside the class that will contain the parsed values.
 *
 * @param classModel The class type that will contain the parse value.
 * @param jsonObject The API response object.
 * @return Returns a generic class containing the values from the json, null if exception occurs.
 *//* w  w w  .java  2s  . co m*/
public static <T> T parse(Class<T> classModel, JSONObject jsonObject) {
    Object object = getNewInstance(classModel);

    if (object != null) {
        // TODO this solution is much accurate but not flexible when using a 3rd party library
        // for object model creation like squidb from yahoo, annotation should be added to the class method
        // and we cannot do that on squidb generated Class model.
        for (Method method : classModel.getDeclaredMethods()) {
            if (method.isAnnotationPresent(SetterSpec.class)) {
                SetterSpec methodLinker = method.getAnnotation(SetterSpec.class);
                String jsonKey = methodLinker.jsonKey();

                initMethodInvocation(method, object, jsonKey, jsonObject);
            }
        }
        return classModel.cast(object);
    } else {
        return null;
    }
}

From source file:pt.webdetails.cpf.SimpleContentGenerator.java

/**
 * Get a map of all public methods with the Exposed annotation.
 * Map is not thread-safe and should be used read-only.
 * @param classe Class where to find methods
 * @param log classe's logger//from www .j  av  a2  s .  c  om
 * @param lowerCase if keys should be in lower case.
 * @return map of all public methods with the Exposed annotation
 */
protected static Map<String, Method> getExposedMethods(Class<?> classe, boolean lowerCase) {
    HashMap<String, Method> exposedMethods = new HashMap<String, Method>();
    Log log = LogFactory.getLog(classe);
    for (Method method : classe.getMethods()) {
        if (method.getAnnotation(Exposed.class) != null) {
            String methodKey = method.getName().toLowerCase();
            if (exposedMethods.containsKey(methodKey)) {
                log.error("Method " + method + " differs from " + exposedMethods.get(methodKey)
                        + " only in case and will override calls to it!!");
            }
            log.debug("registering " + classe.getSimpleName() + "." + method.getName());
            exposedMethods.put(methodKey, method);
        }
    }
    return exposedMethods;
}

From source file:controllers.QController.java

/**
 * Check all the valid HTTP methods supported by the requested API method.
 * //from  w ww  . jav a  2  s.  c om
 * @param m
 *            Reflected method obtained from Play.
 */
private static void checkRequestHttpMethod(Method m) {
    Methods ann = m.getAnnotation(Methods.class);

    HttpMethod method = null;
    if (ann != null) {
        try {
            method = HttpMethod.valueOf(request.method);
        } catch (IllegalArgumentException e) {
            badRequest("Unknown HTTP method.");
        }

        int pos = Arrays.binarySearch(ann.value(), method);
        if (pos < 0) {
            badRequest("This method requires a " + StringUtils.join(ann.value(), " or ") + ".");
        }
    }
}

From source file:controllers.QController.java

/**
 * Check if authentication is required by the requested API method.
 * /*from w  ww. j av  a 2s . c  om*/
 * It renders the errors in an independent way because it needs to throw an
 * unauthorized response (Play works with Exceptions as renderers).
 * 
 * @param m
 *            Reflected method obtained from Play.
 */
private static void checkIfAuthenticationIsRequired(Method m) {
    Annotation ann = m.getAnnotation(RequiresAuthentication.class);

    if (ann != null) {
        if (request.user == null || request.password == null) {
            // We don't have all the required authentication info.
            unauthorized();
        } else {
            switch (authenticate().getResult()) {
            case NOT_VALID:
                unauthorized();
                break;
            case ERROR:
                renderError(500, "Could not authenticate you.");
            }
        }
    }
}

From source file:controllers.QController.java

/**
 * Check all the valid formats supported by the requested API method.
 * //w w  w .ja  va2 s  .c o  m
 * @param m
 *            Reflected method obtained from Play.
 */
private static void checkRequestedFormat(Method m) {
    Formats ann = m.getAnnotation(Formats.class);

    Format format = null;
    if (ann == null) {
        // Assumes raw format if no one configured in class.
        format = Format.RAW;
    } else {
        try {
            // All URLs end in .format
            String sFormat = request.path.substring(request.path.lastIndexOf(".") + 1);
            format = Format.valueOf(sFormat.toUpperCase(Locale.US));
        } catch (IllegalArgumentException e) {
            notAcceptable();
        }

        int pos = Arrays.binarySearch(ann.value(), format);
        if (pos < 0) {
            notAcceptable();
        }
    }

    Cache.set(getFormatKey(), format);
}