Retrieve the value of the "value" attribute of a single-element Annotation, given an annotation instance. - Java java.lang.annotation

Java examples for java.lang.annotation:Annotation Element

Description

Retrieve the value of the "value" attribute of a single-element Annotation, given an annotation instance.

Demo Code

/*//from   www .  j a  v  a  2s. c  o m
 * Copyright 2002-2010 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
//package com.java2s;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

public class Main {
    /** The attribute name for annotations with a single element */
    static final String VALUE = "value";

    /**
     * Retrieve the <em>value</em> of the <code>&quot;value&quot;</code> attribute of a
     * single-element Annotation, given an annotation instance.
     * @param annotation the annotation instance from which to retrieve the value
     * @return the attribute value, or <code>null</code> if not found
     * @see #getValue(Annotation, String)
     */
    public static Object getValue(Annotation annotation) {
        return getValue(annotation, VALUE);
    }

    /**
     * Retrieve the <em>value</em> of a named Annotation attribute, given an annotation instance.
     * @param annotation the annotation instance from which to retrieve the value
     * @param attributeName the name of the attribute value to retrieve
     * @return the attribute value, or <code>null</code> if not found
     * @see #getValue(Annotation)
     */
    public static Object getValue(Annotation annotation,
            String attributeName) {
        try {
            Method method = annotation.annotationType().getDeclaredMethod(
                    attributeName, new Class[0]);
            return method.invoke(annotation);
        } catch (Exception ex) {
            return null;
        }
    }
}

Related Tutorials