Example usage for java.lang.reflect Method getDefaultValue

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

Introduction

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

Prototype

public Object getDefaultValue() 

Source Link

Document

Returns the default value for the annotation member represented by this Method instance.

Usage

From source file:X.java

public static void main(String[] args) {
    try {//from   www .j  ava2  s .  c  o  m
        Class<?> clazz = Class.forName("X");
        X x = (X) clazz.newInstance();
        Class[] argTypes = { String.class };
        Method method = clazz.getMethod("objectMethod", argTypes);

        System.out.println(method.getDefaultValue());

    } catch (Exception e) {
        System.err.println(e);
    }
}

From source file:Util.java

@SuppressWarnings("unchecked")
public static <T> T getAnnotationDefault(Class<? extends Annotation> annotationClass, String element)
        throws Exception {
    Method method = annotationClass.getMethod(element, (Class[]) null);
    return ((T) method.getDefaultValue());
}

From source file:cz.jirutka.validator.collection.internal.AnnotationUtils.java

/**
 * Creates instance (proxy) of the specified annotation with the given
 * attributes./*from w  ww  .ja  va 2  s  .com*/
 *
 * @param annotationType The annotation's class.
 * @param attributes A map with attribute values for the annotation to be created.
 * @param <T> The type of the annotation.
 *
 * @return An instance of the annotation.
 * @throws IllegalArgumentException if some attribute has wrong type or
 *         a required attribute is missing.
 */
public static <T extends Annotation> T createAnnotation(Class<T> annotationType,
        Map<String, Object> attributes) {

    // check if given attributes are defined in annotation
    for (Iterator<String> it = attributes.keySet().iterator(); it.hasNext();) {
        String name = it.next();
        Object value = attributes.get(name);

        if (value == null) {
            LOG.warn("Attribute's value must not be null; will be ignored");
            it.remove();
            continue;
        }
        if (!hasAttribute(annotationType, name)) {
            LOG.warn("Annotation {} does not define attribute: {}; will be ignored", annotationType.getName(),
                    name);
            it.remove();
            continue;
        }
        Class<?> attrType = getAttributeType(annotationType, name);

        Validate.isTrue(isAssignable(value.getClass(), attrType),
                "Attribute '%s' expects %s, but given: %s (%s)", name, attrType.getName(), value,
                value.getClass().getName());
    }
    // check if required attributes are given
    for (Method m : annotationType.getDeclaredMethods()) {
        Validate.isTrue(attributes.containsKey(m.getName()) || m.getDefaultValue() != null,
                "Missing required attribute: %s", m.getName());
    }

    AnnotationDescriptor<T> descriptor = AnnotationDescriptor.getInstance(annotationType, attributes);

    return AnnotationFactory.create(descriptor);
}

From source file:org.apache.sling.contextaware.config.impl.metadata.AnnotationClassParser.java

@SuppressWarnings("unchecked")
private static <T> PropertyMetadata<T> buildPropertyMetadata(Method propertyMethod, Class<T> type) {
    String propertyName = getPropertyName(propertyMethod.getName());
    PropertyMetadata<T> propertyMetadata = new PropertyMetadata<>(propertyName, type);
    propertyMetadata.setDefaultValue((T) propertyMethod.getDefaultValue());

    Property propertyAnnotation = propertyMethod.getAnnotation(Property.class);
    if (propertyAnnotation != null) {
        propertyMetadata.setLabel(emptyToNull(propertyAnnotation.label()));
        propertyMetadata.setDescription(emptyToNull(propertyAnnotation.description()));
        propertyMetadata.setProperties(propsArrayToMap(propertyAnnotation.property()));
    } else {/*w  ww. j ava  2s  . c o  m*/
        Map<String, String> emptyMap = Collections.emptyMap();
        propertyMetadata.setProperties(emptyMap);
    }

    return propertyMetadata;
}

From source file:ch.aonyx.broker.ib.api.util.AnnotationUtils.java

/**
 * Retrieve the <em>default value</em> of a named Annotation attribute, given the {@link Class annotation type}.
 * /*from  w w  w .  j  a  v a2s .  c  o m*/
 * @param annotationType
 *            the <em>annotation type</em> for which the default value should be retrieved
 * @param attributeName
 *            the name of the attribute value to retrieve.
 * @return the default value of the named attribute, or <code>null</code> if not found
 * @see #getDefaultValue(Annotation, String)
 */
public static Object getDefaultValue(final Class<? extends Annotation> annotationType,
        final String attributeName) {
    try {
        final Method method = annotationType.getDeclaredMethod(attributeName, new Class[0]);
        return method.getDefaultValue();
    } catch (final Exception ex) {
        return null;
    }
}

From source file:org.neo4j.ogm.metadata.AnnotationInfo.java

private static String convert(Method element, Object value) {

    final Class<?> returnType = element.getReturnType();
    if (returnType.isPrimitive()) {
        return String.valueOf(value);
    } else if (returnType.equals(Class.class)) {
        return ((Class) value).getName();
    } else {//from   ww w  . j  a  va  2  s. c  o m
        final String result = value.toString();
        if (result.isEmpty()) {
            if (element.getDefaultValue().toString().isEmpty()) {
                return null;
            }
            return element.getDefaultValue().toString();
        }
        return result;
    }
}

From source file:org.dimitrovchi.conf.service.ServiceParameterUtils.java

public static <P> P parameters(final String prefix, final Environment environment) {
    final AnnotationParameters aParameters = annotationParameters();
    return (P) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
            aParameters.annotations.toArray(new Class[aParameters.annotations.size()]),
            new InvocationHandler() {
                @Override/*w  w  w . j a v  a 2  s .  c o m*/
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    if ("toString".equals(method.getName())) {
                        return reflectToString(prefix, proxy);
                    }
                    return environment.getProperty(prefix + "." + method.getName(),
                            (Class) method.getReturnType(), method.getDefaultValue());
                }
            });
}

From source file:com.github.valdr.thirdparty.spring.AnnotationUtils.java

/**
 * Retrieve the <em>default value</em> of a named Annotation attribute, given the {@link Class annotation type}.
 * @param annotationType the <em>annotation type</em> for which the default value should be retrieved
 * @param attributeName the name of the attribute value to retrieve.
 * @return the default value of the named attribute, or {@code null} if not found
 * @see #getDefaultValue(java.lang.annotation.Annotation, String)
 *///from   w w w  .  j  a va2  s .  c o m
public static Object getDefaultValue(Class<? extends Annotation> annotationType, String attributeName) {
    try {
        Method method = annotationType.getDeclaredMethod(attributeName, new Class[0]);
        return method.getDefaultValue();
    } catch (Exception ex) {
        return null;
    }
}

From source file:ReflectUtil.java

/**
 * <p>A better (more concise) toString method for annotation types that yields a String
 * that should look more like the actual usage of the annotation in a class. The String produced
 * is similar to that produced by calling toString() on the annotation directly, with the
 * following differences:</p>/*from   ww w .j a va2  s.  com*/
 *
 * <ul>
 *   <li>Uses the classes simple name instead of it's fully qualified name.</li>
 *   <li>Only outputs attributes that are set to non-default values.</li>
 *
 * <p>If, for some unforseen reason, an exception is thrown within this method it will be
 * caught and the return value will be {@code ann.toString()}.
 *
 * @param ann the annotation to convert to a human readable String
 * @return a human readable String form of the annotation and it's attributes
 */
public static String toString(Annotation ann) {
    try {
        Class<? extends Annotation> type = ann.annotationType();
        StringBuilder builder = new StringBuilder(128);
        builder.append("@");
        builder.append(type.getSimpleName());

        boolean appendedAnyParameters = false;
        Method[] methods = type.getMethods();
        for (Method method : methods) {
            if (!INHERITED_ANNOTATION_METHODS.contains(method.getName())) {
                Object defaultValue = method.getDefaultValue();
                Object actualValue = method.invoke(ann);

                // If we have arrays, they have to be treated a little differently
                Object[] defaultArray = null, actualArray = null;
                if (Object[].class.isAssignableFrom(method.getReturnType())) {
                    defaultArray = (Object[]) defaultValue;
                    actualArray = (Object[]) actualValue;
                }

                // Only print an attribute if it isn't set to the default value
                if ((defaultArray != null && !Arrays.equals(defaultArray, actualArray))
                        || (defaultArray == null && !actualValue.equals(defaultValue))) {

                    if (appendedAnyParameters) {
                        builder.append(", ");
                    } else {
                        builder.append("(");
                    }

                    builder.append(method.getName());
                    builder.append("=");

                    if (actualArray != null) {
                        builder.append(Arrays.toString(actualArray));
                    } else {
                        builder.append(actualValue);
                    }

                    appendedAnyParameters = true;
                }
            }
        }

        if (appendedAnyParameters) {
            builder.append(")");
        }

        return builder.toString();
    } catch (Exception e) {
        return ann.toString();
    }
}

From source file:org.dimitrovchi.conf.service.ServiceParameterUtils.java

@SuppressWarnings({ "element-type-mismatch" })
public static <P> P mergeAnnotationParameters() {
    final AnnotationParameters aParameters = annotationParameters();
    return (P) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
            aParameters.annotations.toArray(new Class[aParameters.annotations.size()]),
            new InvocationHandler() {
                @Override/* w  w w. j  ava 2s  .c  o  m*/
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    if ("toString".equals(method.getName())) {
                        return reflectToString(aParameters.topCaller.getSimpleName(), proxy);
                    }
                    final Class<?> annotationClass = method.getDeclaringClass();
                    final List<Annotation> annotations = aParameters.annotationMap.containsKey(annotationClass)
                            ? aParameters.annotationMap.get(annotationClass)
                            : Collections.<Annotation>emptyList();
                    for (final Annotation annotation : annotations) {
                        final Object value = method.invoke(annotation, args);
                        if (!Objects.deepEquals(method.getDefaultValue(), value)) {
                            return value;
                        }
                    }
                    return method.getDefaultValue();
                }
            });
}