Example usage for java.lang Class getAnnotation

List of usage examples for java.lang Class getAnnotation

Introduction

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

Prototype

@SuppressWarnings("unchecked")
public <A extends Annotation> A getAnnotation(Class<A> annotationClass) 

Source Link

Usage

From source file:com.smartitengineering.util.bean.BeanFactoryRegistrar.java

private static boolean aggregate(Class<? extends Object> aggregatorClass, Object aggregator)
        throws SecurityException {
    if (aggregatorClass.equals(Object.class)) {
        return true;
    }//from  w w w. j  av a 2  s.  c o m
    Class<? extends Object> superClass = aggregatorClass.getSuperclass();
    if (superClass != null) {
        aggregate(superClass, aggregator);
    }
    Aggregator aggregatorAnnotation = aggregatorClass.getAnnotation(Aggregator.class);
    if (aggregatorAnnotation == null || StringUtils.isBlank(aggregatorAnnotation.contextName())) {
        return true;
    }
    BeanFactory beanFactory = getBeanFactorForContext(aggregatorAnnotation.contextName());
    if (beanFactory == null) {
        return true;
    }
    Field[] declaredFields = aggregatorClass.getDeclaredFields();
    for (Field declaredField : declaredFields) {
        InjectableField injectableField = declaredField.getAnnotation(InjectableField.class);
        if (injectableField == null) {
            continue;
        }
        String beanName = StringUtils.isBlank(injectableField.beanName()) && beanFactory.isNameMandatory()
                ? declaredField.getName()
                : injectableField.beanName();
        if (StringUtils.isBlank(beanName) && beanFactory.isNameMandatory()) {
            return true;
        }
        try {
            declaredField.setAccessible(true);
            final Class<?> fieldType = declaredField.getType();
            if (beanFactory.containsBean(beanName, fieldType)) {
                declaredField.set(aggregator, beanFactory.getBean(beanName, fieldType));
            }
        } catch (IllegalArgumentException ex) {
            ex.printStackTrace();
        } catch (IllegalAccessException ex) {
            ex.printStackTrace();
        }

    }
    return false;
}

From source file:org.jdbcluster.metapersistence.cluster.ClusterFactory.java

/**
 * get the cluster class object from a Dao instance
 * @param dao Dao instance to search cluster
 * @return Class<? extends Cluster> class of corresponding cluster
 *//*  w w w .  ja  v a2 s . c  om*/
@SuppressWarnings("unchecked")
public static Class<? extends Cluster> getClusterFromDao(Object dao) {

    Assert.notNull(dao, "Dao dao may not be null");

    List<String> clusterIDs = ClusterTypeBase.getClusterTypeConfig().getClusterIDs();
    for (String s : clusterIDs) {
        Class<? extends Cluster> clusterClass = null;
        String className = ClusterTypeBase.getClusterTypeConfig().getClusterClassName(s);
        try {
            clusterClass = (Class<? extends Cluster>) Class.forName(className);
            DaoLink classAnno = clusterClass.getAnnotation(DaoLink.class);
            if (classAnno != null) {
                if (classAnno.dAOClass() == dao.getClass())
                    return clusterClass;
            }
        } catch (ClassNotFoundException e) {
            throw new ClusterTypeException(
                    "no definition for the class [" + className + "] with the specified name could be found",
                    e);
        }
    }
    return null;
}

From source file:be.fedict.eid.applet.maven.DocbookMojo.java

private static BasicVisualizationServer<String, String> createGraph() {
    AppletProtocolMessageCatalog catalog = new AppletProtocolMessageCatalog();
    List<Class<?>> catalogClasses = catalog.getCatalogClasses();

    Map<ProtocolState, List<String>> allowedProtocolStates = new HashedMap<ProtocolState, List<String>>();
    String startMessage = null;//from w  w  w. j a  v  a 2  s  .co m
    List<String> stopMessages = new LinkedList<String>();

    Graph<String, String> graph = new SparseMultigraph<String, String>();
    for (Class<?> messageClass : catalogClasses) {
        StartRequestMessage startRequestMessageAnnotation = messageClass
                .getAnnotation(StartRequestMessage.class);
        if (null != startRequestMessageAnnotation) {
            if (null != startMessage) {
                throw new RuntimeException("only one single entry point possible");
            }
            startMessage = messageClass.getSimpleName();
        }
        StopResponseMessage stopResponseMessageAnnotation = messageClass
                .getAnnotation(StopResponseMessage.class);
        if (null != stopResponseMessageAnnotation) {
            stopMessages.add(messageClass.getSimpleName());
        }
        graph.addVertex(messageClass.getSimpleName());
        ProtocolStateAllowed protocolStateAllowedAnnotation = messageClass
                .getAnnotation(ProtocolStateAllowed.class);
        if (null != protocolStateAllowedAnnotation) {
            ProtocolState protocolState = protocolStateAllowedAnnotation.value();
            List<String> messages = allowedProtocolStates.get(protocolState);
            if (null == messages) {
                messages = new LinkedList<String>();
                allowedProtocolStates.put(protocolState, messages);
            }
            messages.add(messageClass.getSimpleName());
        }
    }

    int edgeIdx = 0;
    for (Class<?> messageClass : catalogClasses) {
        ResponsesAllowed responsesAllowedAnnotation = messageClass.getAnnotation(ResponsesAllowed.class);
        if (null != responsesAllowedAnnotation) {
            Class<?>[] responseClasses = responsesAllowedAnnotation.value();
            for (Class<?> responseClass : responseClasses) {
                String edgeName = "edge-" + edgeIdx;
                graph.addEdge(edgeName, messageClass.getSimpleName(), responseClass.getSimpleName(),
                        EdgeType.DIRECTED);
                edgeIdx++;
            }
        }
        StateTransition stateTransitionAnnotation = messageClass.getAnnotation(StateTransition.class);
        if (null != stateTransitionAnnotation) {
            ProtocolState protocolState = stateTransitionAnnotation.value();
            List<String> messages = allowedProtocolStates.get(protocolState);
            for (String message : messages) {
                graph.addEdge("edge-" + edgeIdx, messageClass.getSimpleName(), message, EdgeType.DIRECTED);
                edgeIdx++;
            }
        }
    }

    Layout<String, String> layout = new CircleLayout<String, String>(graph);
    layout.setSize(new Dimension(900, 600));

    BasicVisualizationServer<String, String> visualization = new BasicVisualizationServer<String, String>(
            layout);
    visualization.getRenderContext().setVertexLabelTransformer(new ToStringLabeller<String>());
    Transformer<String, Paint> myVertexTransformer = new MyVertexTransformer(startMessage, stopMessages);
    visualization.getRenderContext().setVertexFillPaintTransformer(myVertexTransformer);
    Transformer<String, Paint> myEdgeTransformer = new MyEdgeTransformer();
    visualization.getRenderContext().setEdgeDrawPaintTransformer(myEdgeTransformer);
    visualization.getRenderer().getVertexLabelRenderer().setPosition(Position.AUTO);
    visualization.setPreferredSize(new Dimension(900, 650));
    visualization.setBackground(Color.WHITE);
    return visualization;
}

From source file:eagle.log.entity.meta.EntityDefinitionManager.java

/**
 * Check whether the entity class is time series, false by default
 * @param clazz/*from w w w  .j  ava2  s  .  c  om*/
 * @return
 */
public static boolean isTimeSeries(Class<? extends TaggedLogAPIEntity> clazz) {
    TimeSeries ts = clazz.getAnnotation(TimeSeries.class);
    return ts != null && ts.value();
}

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

/**
 * Find a single {@link java.lang.annotation.Annotation} of {@code annotationType} from the supplied {@link Class},
 * traversing its interfaces and superclasses if no annotation can be found on the given class itself.
 * <p>This method explicitly handles class-level annotations which are not declared as
 * {@link java.lang.annotation.Inherited inherited} <i>as well as annotations on interfaces</i>.
 * <p>The algorithm operates as follows: Searches for an annotation on the given class and returns
 * it if found. Else searches all interfaces that the given class declares, returning the annotation
 * from the first matching candidate, if any. Else proceeds with introspection of the superclass
 * of the given class, checking the superclass itself; if no annotation found there, proceeds
 * with the interfaces that the superclass declares. Recursing up through the entire superclass
 * hierarchy if no match is found.//ww w.  j  av a 2 s .  c o  m
 * @param clazz the class to look for annotations on
 * @param annotationType the annotation class to look for
 * @return the annotation found, or {@code null} if none found
 */
public static <A extends Annotation> A findAnnotation(Class<?> clazz, Class<A> annotationType) {
    A annotation = clazz.getAnnotation(annotationType);
    if (annotation != null) {
        return annotation;
    }
    for (Class<?> ifc : clazz.getInterfaces()) {
        annotation = findAnnotation(ifc, annotationType);
        if (annotation != null) {
            return annotation;
        }
    }
    if (!Annotation.class.isAssignableFrom(clazz)) {
        for (Annotation ann : clazz.getAnnotations()) {
            annotation = findAnnotation(ann.annotationType(), annotationType);
            if (annotation != null) {
                return annotation;
            }
        }
    }
    Class<?> superClass = clazz.getSuperclass();
    if (superClass == null || superClass.equals(Object.class)) {
        return null;
    }
    return findAnnotation(superClass, annotationType);
}

From source file:edu.umich.flowfence.sandbox.ResolvedQM.java

protected static <TAnnot extends Annotation, TMember extends AnnotatedElement & Member> TAnnot getMatchingAnnotation(
        Class<TAnnot> annotClass, TMember member) {
    TAnnot annot = member.getAnnotation(annotClass);
    if (annot != null) {
        return annot;
    }/*from   w w  w . j av  a  2  s .com*/

    Class<?> declaringClass = member.getDeclaringClass();
    annot = declaringClass.getAnnotation(annotClass);
    if (annot != null) {
        return annot;
    }

    Package declaringPackage = declaringClass.getPackage();
    annot = declaringPackage.getAnnotation(annotClass);
    if (annot != null) {
        return annot;
    }

    return null;
}

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

/**
 * Find a single {@link Annotation} of <code>annotationType</code> from the supplied {@link Class}, traversing its
 * interfaces and superclasses if no annotation can be found on the given class itself.
 * <p>//from  w  ww . j a  v a2  s.com
 * This method explicitly handles class-level annotations which are not declared as
 * {@link java.lang.annotation.Inherited inherited} <i>as well as annotations on interfaces</i>.
 * <p>
 * The algorithm operates as follows: Searches for an annotation on the given class and returns it if found. Else
 * searches all interfaces that the given class declares, returning the annotation from the first matching
 * candidate, if any. Else proceeds with introspection of the superclass of the given class, checking the superclass
 * itself; if no annotation found there, proceeds with the interfaces that the superclass declares. Recursing up
 * through the entire superclass hierarchy if no match is found.
 * 
 * @param clazz
 *            the class to look for annotations on
 * @param annotationType
 *            the annotation class to look for
 * @return A tuple {@link Pair} containing the annotation on the left hand side and the class on the right hand side
 *         or <code>null</code> if none found
 */
public static <A extends Annotation> Pair<A, Class<?>> findAnnotation(final Class<?> clazz,
        final Class<A> annotationType) {
    Validate.notNull(clazz, "Class must not be null");
    A annotation = clazz.getAnnotation(annotationType);
    if (annotation != null) {
        return new ImmutablePair<A, Class<?>>(annotation, clazz);
    }
    for (final Class<?> ifc : clazz.getInterfaces()) {
        final Pair<A, Class<?>> pair = findAnnotation(ifc, annotationType);
        if (pair != null) {
            annotation = pair.getLeft();
            if (annotation != null) {
                return new ImmutablePair<A, Class<?>>(annotation, ifc);
            }
        }
    }
    if (!Annotation.class.isAssignableFrom(clazz)) {
        for (final Annotation ann : clazz.getAnnotations()) {
            final Pair<A, Class<?>> pair = findAnnotation(ann.annotationType(), annotationType);
            if (pair != null) {
                annotation = pair.getLeft();
                if (annotation != null) {
                    return new ImmutablePair<A, Class<?>>(annotation, ann.annotationType());
                }
            }
        }
    }
    final Class<?> superClass = clazz.getSuperclass();
    if ((superClass == null) || (superClass == Object.class)) {
        return null;
    }
    return findAnnotation(superClass, annotationType);
}

From source file:com.manydesigns.portofino.logic.SecurityLogic.java

public static RequiresPermissions getRequiresPermissionsAnnotation(Method handler, Class<?> theClass) {
    RequiresPermissions requiresPermissions = handler.getAnnotation(RequiresPermissions.class);
    if (requiresPermissions != null) {
        logger.debug("Action method requires specific permissions: {}", handler);
    } else {/*w  w w . j a va 2 s  .  co  m*/
        requiresPermissions = theClass.getAnnotation(RequiresPermissions.class);
        if (requiresPermissions != null) {
            logger.debug("Action class requires specific permissions: {}", theClass);
        }
    }
    return requiresPermissions;
}

From source file:com.pandich.dropwizard.curator.refresh.Refresher.java

private static String getNodePath(final Class<?> clazz, final String name, final CuratorInject curatorInject) {

    final String path;

    if (startsWith(curatorInject.value(), PATH_DELIMITER)) {
        path = curatorInject.value();/* w  ww. jav  a 2 s  .  c om*/
    } else {
        final String rootPath;
        final CuratorRoot curatorRoot = clazz.getAnnotation(CuratorRoot.class);
        if (curatorRoot != null && !isBlank(curatorRoot.value())) {
            rootPath = curatorRoot.value();
        } else {
            final String underscoreClassName = UPPER_CAMEL.to(LOWER_UNDERSCORE, clazz.getSimpleName());
            final String[] pieces = split(underscoreClassName, "_");
            rootPath = join(subarray(pieces, 0, pieces.length - 1));
        }

        final String nodeSubPath = defaultIfBlank(curatorInject.value(), name);
        final String normalizedRootPath = strip(rootPath, PATH_DELIMITER);
        path = lowerCase(PATH_DELIMITER + normalizedRootPath + PATH_DELIMITER + nodeSubPath);
    }

    log.debug("path: {}.{}={}", new Object[] { clazz.getSimpleName(), name, path });
    return path;
}

From source file:com.evolveum.midpoint.repo.sql.util.RUtil.java

public static String getTableName(Class hqlType) {
    Table tableAnnotation = (Table) hqlType.getAnnotation(Table.class); // TODO what about performance here? (synchronized call)
    if (tableAnnotation != null && StringUtils.isNotEmpty(tableAnnotation.name())) {
        return tableAnnotation.name();
    }//  w  w w  .  j  a  v a 2s . com
    MidPointNamingStrategy namingStrategy = new MidPointNamingStrategy();
    return namingStrategy.classToTableName(hqlType.getSimpleName());
}