Example usage for java.lang Class isAnnotationPresent

List of usage examples for java.lang Class isAnnotationPresent

Introduction

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

Prototype

@Override
public boolean isAnnotationPresent(Class<? extends Annotation> annotationClass) 

Source Link

Usage

From source file:org.nerve.utils.reflection.ReflectionUtils.java

public static <T extends Annotation> T getAnnotation(Class targetClass, Class annotationClass) {
    Assert.notNull(targetClass, "targetClass?");
    Assert.notNull(annotationClass, "annotationClass?");

    if (targetClass.isAnnotationPresent(annotationClass)) {
        return (T) targetClass.getAnnotation(annotationClass);
    }//from  www  .j  ava 2 s . c  o m

    return null;
}

From source file:org.guzz.builder.JPA2AnnotationsBuilder.java

/**
 * Build the {@link Business} and the {@link Table} information of the domain class.
 * <p/>//w  ww  .j av  a2 s .  com
 * We have to seperate this operation from the {@link #parseClassForAttributes(GuzzContextImpl, POJOBasedObjectMapping, Business, DBGroup, SimpleTable, Class)}
 *  to get the final "dbGroup" after the inherited tree.
 */
protected static void parseClassForEntityTable(DomainInfo info, Class domainClass) {
    //???
    Class parentCls = domainClass.getSuperclass();
    if (parentCls != null && parentCls.isAnnotationPresent(MappedSuperclass.class)) {
        parseClassForEntityTable(info, parentCls);
    }

    //?
    org.guzz.annotations.Entity ge = (org.guzz.annotations.Entity) domainClass
            .getAnnotation(org.guzz.annotations.Entity.class);
    org.guzz.annotations.Table gt = (org.guzz.annotations.Table) domainClass
            .getAnnotation(org.guzz.annotations.Table.class);
    javax.persistence.Table pt = (javax.persistence.Table) domainClass
            .getAnnotation(javax.persistence.Table.class);

    if (ge != null) {
        info.businessName = ge.businessName();

        Class m_interpreter = ge.interpreter();
        if (m_interpreter != null && !NullValue.class.isAssignableFrom(m_interpreter)) {
            info.interpreter = m_interpreter;
        }
    }

    if (pt != null) {
        if (StringUtil.notEmpty(pt.name())) {
            info.tableName = pt.name();
        }
    }

    if (gt != null) {
        if (StringUtil.notEmpty(gt.dbGroup())) {
            info.dbGroup = gt.dbGroup();
        }
        if (StringUtil.notEmpty(gt.name())) {
            info.tableName = gt.name();
        }
        if (gt.shadow() != null) {
            info.shadow = gt.shadow();
        }

        info.dynamicUpdate = gt.dynamicUpdate();
    }

}

From source file:org.guzz.builder.JPA2AnnotationsBuilder.java

/**
 * Only retrieve {@link SequenceGenerator} and {@link TableGenerator} in the type declaration.
 *///  w ww  . j a v a  2 s . c  o  m
public static void parseForIdGenerators(final Map idGenerators, Class domainCls) throws ClassNotFoundException {
    javax.persistence.Entity pe = (javax.persistence.Entity) domainCls
            .getAnnotation(javax.persistence.Entity.class);
    javax.persistence.MappedSuperclass pm = (javax.persistence.MappedSuperclass) domainCls
            .getAnnotation(javax.persistence.MappedSuperclass.class);

    if (pe == null && pm == null) {
        log.debug("Parsing for id generator ends at class:" + domainCls.getName());
        return;
    }

    //parse the super class first, then add/replace it from the subclass.
    Class superCls = domainCls.getSuperclass();
    if (superCls != null && superCls.isAnnotationPresent(javax.persistence.MappedSuperclass.class)) {
        parseForIdGenerators(idGenerators, superCls);
    }

    //parse for this class.
    SequenceGenerator psg = (SequenceGenerator) domainCls.getAnnotation(SequenceGenerator.class);
    TableGenerator tsg = (TableGenerator) domainCls.getAnnotation(TableGenerator.class);

    GenericGenerator[] ggs = new GenericGenerator[0];

    //add @GenericGenerators
    if (domainCls.getPackage().isAnnotationPresent(GenericGenerators.class)) {
        ggs = (GenericGenerator[]) ArrayUtil.addToArray(ggs,
                ((GenericGenerators) domainCls.getPackage().getAnnotation(GenericGenerators.class)).value());
    }
    if (domainCls.isAnnotationPresent(GenericGenerators.class)) {
        ggs = (GenericGenerator[]) ArrayUtil.addToArray(ggs,
                ((GenericGenerators) domainCls.getAnnotation(GenericGenerators.class)).value());
    }

    //add @GenericGenerator
    if (domainCls.getPackage().isAnnotationPresent(GenericGenerator.class)) {
        ggs = (GenericGenerator[]) ArrayUtil.addToArray(ggs,
                (GenericGenerator) domainCls.getPackage().getAnnotation(GenericGenerator.class));
    }
    if (domainCls.isAnnotationPresent(GenericGenerator.class)) {
        ggs = (GenericGenerator[]) ArrayUtil.addToArray(ggs,
                (GenericGenerator) domainCls.getAnnotation(GenericGenerator.class));
    }

    if (psg != null) {
        String name = psg.name();
        if (idGenerators.get(name) != null && log.isDebugEnabled()) {
            log.debug("override @Id annotation:[" + idGenerators.get(name)
                    + "] with @SequenceGenerator, name is:" + name);
        }

        idGenerators.put(name, psg);
    }

    if (tsg != null) {
        String name = tsg.name();
        if (idGenerators.get(name) != null && log.isDebugEnabled()) {
            log.debug("override @Id annotation:[" + idGenerators.get(name) + "] with @TableGenerator, name is:"
                    + name);
        }

        idGenerators.put(name, tsg);
    }

    if (ggs.length > 0) {
        for (GenericGenerator gg : ggs) {
            String name = gg.name();
            if (idGenerators.get(name) != null && log.isDebugEnabled()) {
                log.debug("override @Id annotation:[" + idGenerators.get(name)
                        + "] with @GenericGenerator, name is:" + name);
            }

            idGenerators.put(name, gg);
        }
    }
}

From source file:org.squidy.common.util.ReflectionUtil.java

/**
 * @param classLoader//w w  w  .j  a v  a 2  s . c  om
 * @param classNames
 * @param augmentClasses
 * @return
 */
public static Class<?>[] loadContextClasses(ClassLoader classLoader, String[] classNames,
        Class<?>... augmentClasses) {
    List<Class<?>> classes = new ArrayList<Class<?>>();

    // Augment context classes with augment classes.
    for (Class<?> type : augmentClasses) {
        classes.add(type);
    }

    for (String className : classNames) {
        Class<?> type = null;
        try {
            className = className.replace('/', '.');
            type = classLoader.loadClass(className);
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        if (type != null) {
            if (type.isAnnotationPresent(XmlType.class)) {
                classes.add(type);
            }
        }
    }
    return classes.toArray(new Class[0]);
}

From source file:com.github.abel533.mapperhelper.EntityHelper.java

/**
 * ?//from   ww  w .j a  v a2  s.  c o  m
 *
 * @param entityClass
 */
public static synchronized void initEntityNameMap(Class<?> entityClass) {
    if (entityTableMap.get(entityClass) != null) {
        return;
    }
    //??
    EntityTable entityTable = null;
    if (entityClass.isAnnotationPresent(Table.class)) {
        Table table = entityClass.getAnnotation(Table.class);
        if (!table.name().equals("")) {
            entityTable = new EntityTable();
            entityTable.setTable(table);
        }
    }
    if (entityTable == null) {
        entityTable = new EntityTable();
        //??????@Table
        entityTable.name = camelhumpToUnderline(entityClass.getSimpleName());
    }
    //
    List<Field> fieldList = getAllField(entityClass, null);
    Set<EntityColumn> columnSet = new HashSet<EntityColumn>();
    Set<EntityColumn> pkColumnSet = new HashSet<EntityColumn>();
    for (Field field : fieldList) {
        //
        if (field.isAnnotationPresent(Transient.class)) {
            continue;
        }
        EntityColumn entityColumn = new EntityColumn();
        if (field.isAnnotationPresent(Id.class)) {
            entityColumn.setId(true);
        }
        String columnName = null;
        if (field.isAnnotationPresent(Column.class)) {
            Column column = field.getAnnotation(Column.class);
            columnName = column.name();
        }
        if (columnName == null || columnName.equals("")) {
            columnName = camelhumpToUnderline(field.getName());
        }
        entityColumn.setProperty(field.getName());
        entityColumn.setColumn(columnName.toUpperCase());
        entityColumn.setJavaType(field.getType());
        //order by
        if (field.isAnnotationPresent(OrderBy.class)) {
            OrderBy orderBy = field.getAnnotation(OrderBy.class);
            if (orderBy.value().equals("")) {
                entityColumn.setOrderBy("ASC");
            } else {
                entityColumn.setOrderBy(orderBy.value());
            }
        }
        // - Oracle?MySqlUUID
        if (field.isAnnotationPresent(SequenceGenerator.class)) {
            SequenceGenerator sequenceGenerator = field.getAnnotation(SequenceGenerator.class);
            if (sequenceGenerator.sequenceName().equals("")) {
                throw new RuntimeException(entityClass + "" + field.getName()
                        + "@SequenceGeneratorsequenceName!");
            }
            entityColumn.setSequenceName(sequenceGenerator.sequenceName());
        } else if (field.isAnnotationPresent(GeneratedValue.class)) {
            GeneratedValue generatedValue = field.getAnnotation(GeneratedValue.class);
            if (generatedValue.generator().equals("UUID")) {
                if (field.getType().equals(String.class)) {
                    entityColumn.setUuid(true);
                } else {
                    throw new RuntimeException(field.getName()
                            + " - @GeneratedValue?UUID?String");
                }
            } else if (generatedValue.generator().equals("JDBC")) {
                if (Number.class.isAssignableFrom(field.getType())) {
                    entityColumn.setIdentity(true);
                    entityColumn.setGenerator("JDBC");
                } else {
                    throw new RuntimeException(field.getName()
                            + " - @GeneratedValue?UUID?String");
                }
            } else {
                //?generator??idsql,mysql=CALL IDENTITY(),hsqldb=SELECT SCOPE_IDENTITY()
                //??generator
                if (generatedValue.strategy() == GenerationType.IDENTITY) {
                    //mysql
                    entityColumn.setIdentity(true);
                    if (!generatedValue.generator().equals("")) {
                        String generator = null;
                        MapperHelper.IdentityDialect identityDialect = MapperHelper.IdentityDialect
                                .getDatabaseDialect(generatedValue.generator());
                        if (identityDialect != null) {
                            generator = identityDialect.getIdentityRetrievalStatement();
                        } else {
                            generator = generatedValue.generator();
                        }
                        entityColumn.setGenerator(generator);
                    }
                } else {
                    throw new RuntimeException(field.getName()
                            + " - @GeneratedValue?????:"
                            + "\n1.?@GeneratedValue(generator=\"UUID\")"
                            + "\n2.useGeneratedKeys@GeneratedValue(generator=\\\"JDBC\\\")  "
                            + "\n3.mysql?@GeneratedValue(strategy=GenerationType.IDENTITY[,generator=\"Mysql\"])");
                }
            }
        }
        columnSet.add(entityColumn);
        if (entityColumn.isId()) {
            pkColumnSet.add(entityColumn);
        }
    }
    entityTable.entityClassColumns = columnSet;
    if (pkColumnSet.size() == 0) {
        entityTable.entityClassPKColumns = columnSet;
    } else {
        entityTable.entityClassPKColumns = pkColumnSet;
    }
    //
    entityTableMap.put(entityClass, entityTable);
}

From source file:com.github.gekoh.yagen.ddl.TableConfig.java

private static Class getEntitySuperclass(Class entity) {
    // in case of joined table inheritance the superclass has its own table and we do not need
    // to care about attributes from superclasses
    if (entity.isAnnotationPresent(DiscriminatorValue.class)) {
        return null;
    }/*from   w w w.  jav a 2 s. c  om*/

    // in all other cases we also need to consider attributes/columns of superclasses as they
    // were found in this entity's table
    Class superClass = entity.getSuperclass();

    if (superClass != null && (superClass.isAnnotationPresent(MappedSuperclass.class)
            || superClass.isAnnotationPresent(Entity.class))) {
        return superClass;
    }

    return null;
}

From source file:org.springframework.test.context.ContextLoaderUtils.java

/**
 * Build the {@link MergedContextConfiguration merged context configuration} for
 * the supplied {@link Class testClass} and {@code defaultContextLoaderClassName},
 * taking into account context hierarchies declared via
 * {@link ContextHierarchy @ContextHierarchy} and
 * {@link ContextConfiguration @ContextConfiguration}.
 *
 * @param testClass the test class for which the {@code MergedContextConfiguration}
 * should be built (must not be {@code null})
 * @param defaultContextLoaderClassName the name of the default {@code ContextLoader}
 * class to use (may be {@code null})/* www  .ja  va  2 s.  c o m*/
 * @param cacheAwareContextLoaderDelegate the cache-aware context loader delegate to
 * be passed to the {@code MergedContextConfiguration} constructor
 * @return the merged context configuration
 * @see #buildContextHierarchyMap(Class)
 * @see #buildMergedContextConfiguration(Class, List, String, MergedContextConfiguration, CacheAwareContextLoaderDelegate)
 */
@SuppressWarnings("javadoc")
static MergedContextConfiguration buildMergedContextConfiguration(Class<?> testClass,
        String defaultContextLoaderClassName, CacheAwareContextLoaderDelegate cacheAwareContextLoaderDelegate) {

    if (testClass.isAnnotationPresent(ContextHierarchy.class)) {
        Map<String, List<ContextConfigurationAttributes>> hierarchyMap = buildContextHierarchyMap(testClass);

        MergedContextConfiguration parentConfig = null;
        MergedContextConfiguration mergedConfig = null;

        for (List<ContextConfigurationAttributes> list : hierarchyMap.values()) {
            List<ContextConfigurationAttributes> reversedList = new ArrayList<ContextConfigurationAttributes>(
                    list);
            Collections.reverse(reversedList);

            // Don't use the supplied testClass; instead ensure that we are
            // building the MCC for the actual test class that declared the
            // configuration for the current level in the context hierarchy.
            Assert.notEmpty(reversedList, "ContextConfigurationAttributes list must not be empty");
            Class<?> declaringClass = reversedList.get(0).getDeclaringClass();

            mergedConfig = buildMergedContextConfiguration(declaringClass, reversedList,
                    defaultContextLoaderClassName, parentConfig, cacheAwareContextLoaderDelegate);
            parentConfig = mergedConfig;
        }

        // Return the last level in the context hierarchy
        return mergedConfig;
    } else {
        return buildMergedContextConfiguration(testClass, resolveContextConfigurationAttributes(testClass),
                defaultContextLoaderClassName, null, cacheAwareContextLoaderDelegate);
    }
}

From source file:org.codehaus.enunciate.modules.xfire.EnunciatedJAXWSWebFaultHandler.java

/**
 * Determine whether the fault conforms to the fault pattern described in the JAXWS spec, section 2.5.
 *
 * @param faultClass The fault class./*from  w  w w. j a  v a 2  s . co  m*/
 * @return Whether the fault class conforms to the pattern.
 */
public static boolean conformsToJAXWSFaultPattern(Class<? extends Throwable> faultClass) {
    boolean conformsToJAXWSFaultPattern = false;
    try {
        //1. needs to have a getFaultInfo method.
        Method getFaultInfoMethod = faultClass.getMethod("getFaultInfo");
        //2. needs to have a constructor matching WebFault(String message, FaultBean faultBean) {...}
        faultClass.getConstructor(String.class, getFaultInfoMethod.getReturnType());
        //3. needs to have a constructor matching WebFault(String message, FaultBean faultBean, Throwable cause) {...}
        faultClass.getConstructor(String.class, getFaultInfoMethod.getReturnType(), Throwable.class);

        conformsToJAXWSFaultPattern = faultClass.isAnnotationPresent(WebFault.class);
    } catch (NoSuchMethodException e) {
        //fall through.  doesn't conform to the spec pattern.
    }
    return conformsToJAXWSFaultPattern;
}

From source file:adalid.core.XS1.java

private static void checkAbstractClassReference(Field declaringField, Class<?> type) {
    if (type.isAnnotationPresent(AbstractClass.class)) {
        String message = "Abstract Class Reference: " + declaringField + "; " + type.getSimpleName()
                + " is annotated with AbstractClass";
        if (type.isAnnotationPresent(InheritanceMapping.class)) {
            InheritanceMapping annotation = type.getAnnotation(InheritanceMapping.class);
            message += " and its inheritance mapping strategy is " + annotation.strategy();
            if (InheritanceMappingStrategy.TABLE_PER_CLASS.equals(annotation.strategy())) {
                TLC.getProject().getParser().error(message);
            }/*w  ww  .j  a  v a  2s . c o  m*/
        }
    }
}

From source file:com.conversantmedia.mapreduce.tool.RunJob.java

@SuppressWarnings("unchecked")
protected static Map<String, DriverMeta> findAllDrivers(Reflections reflections) {
    Map<String, DriverMeta> idMap = new TreeMap<>(new Comparator<String>() {
        @Override/*from ww w. j  a  va 2  s.  c  om*/
        public int compare(String s1, String s2) {
            return s1.compareTo(s2);
        }
    });

    for (Class<?> c : reflections.getTypesAnnotatedWith(Driver.class)) {
        Driver d = AnnotationUtils.findAnnotation(c, Driver.class);
        String version = versionForDriverClass(c, d.version());
        String driverId = d.value();
        if (StringUtils.isBlank(driverId)) {
            driverId = MaraAnnotationUtil.INSTANCE.defaultDriverIdForClass(c);
        }
        DriverMeta meta = new DriverMeta(driverId, d.description(), version, c, d.listener());
        idMap.put(driverId, meta);

        if (c.isAnnotationPresent(Hidden.class)) {
            meta.hidden = true;
        }
    }
    // Have to do this 2x - a second time for Tool
    for (Class<?> c : reflections.getTypesAnnotatedWith(Tool.class)) {
        Tool t = AnnotationUtils.findAnnotation(c, Tool.class);
        String version = versionForDriverClass(c, t.version());
        String toolId = t.value();
        if (StringUtils.isBlank(toolId)) {
            toolId = MaraAnnotationUtil.INSTANCE.defaultDriverIdForClass(c);
        }
        DriverMeta meta = new DriverMeta(toolId, t.description(), version, c, t.listener());
        idMap.put(toolId, meta);

        if (c.isAnnotationPresent(Hidden.class)) {
            meta.hidden = true;
        }
    }
    return idMap;
}