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.zlfun.framework.excel.ExcelUtils.java

private static <T> T fill(Map<String, String> map, T t) {
    T bean = t;//from   w  ww.j  ava 2  s .c  o  m
    try {

        if (t.getClass().getAnnotation(WebParam.class) == null) {

            Field[] fs = t.getClass().getDeclaredFields();
            for (Field f : fs) {

                set(bean, f, map.get(f.getName()));

            }
        } else {
            Field[] fs = t.getClass().getDeclaredFields();
            for (Field f : fs) {
                WebParam param = f.getAnnotation(WebParam.class);
                if (param != null) {
                    String fname;
                    if ("".equals(param.value())) {
                        fname = f.getName();
                    } else {
                        fname = param.value();
                    }

                    set(bean, f, map.get(fname));
                }

            }

            // ?
            Class<?> parent = t.getClass().getSuperclass();
            while (parent != Object.class) {

                if (parent.getAnnotation(ItemField.class) != null) {

                    Field[] pfs = parent.getDeclaredFields();
                    for (Field f : pfs) {
                        WebParam param = f.getAnnotation(WebParam.class);
                        if (param != null) {
                            String fname;
                            if ("".equals(param.value())) {
                                fname = f.getName();
                            } else {
                                fname = param.value();
                            }

                            set(bean, f, map.get(fname));
                        }

                    }

                    parent = parent.getSuperclass();
                } else {
                    break;
                }

            }

        }
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return bean;
}

From source file:com.wavemaker.runtime.server.ServerUtils.java

/**
 * Get a list of methods to be exposed to the client. This will obey restrictions from {@link ExposeToClient} and
 * {@link HideFromClient}./*from   w  w w  .j  a  va 2  s . co  m*/
 * 
 * @param klass The class to examine.
 * @return A list of methods to expose to the client in the specified class.
 */
@SuppressWarnings("unchecked")
public static List<Method> getClientExposedMethods(Class<?> klass) {

    List<Method> allMethods = ClassUtils.getPublicMethods(klass);
    List<Method> ret = new ArrayList<Method>(allMethods.size());
    ClassLoader cl = klass.getClassLoader();

    Class<Annotation> hideFromClient = (Class<Annotation>) ClassLoaderUtils
            .loadClass(HideFromClient.class.getCanonicalName(), cl);
    Class<Annotation> exposeToClient = (Class<Annotation>) ClassLoaderUtils
            .loadClass(ExposeToClient.class.getCanonicalName(), cl);

    if (klass.getAnnotation(hideFromClient) != null) {
        for (Method meth : allMethods) {
            if (meth.getAnnotation(exposeToClient) != null) {
                ret.add(meth);
            }
        }
    } else {
        for (Method meth : allMethods) {
            if (meth.getAnnotation(hideFromClient) == null) {
                ret.add(meth);
            }
        }
    }

    return ret;
}

From source file:com.cisco.oss.foundation.logging.structured.AbstractFoundationLoggingMarker.java

private static boolean buildFromAnnotations(Class<? extends FoundationLoggingMarker> clazz,
        StringBuilder builder) {//  w  ww . java2  s.  c  om
    boolean shouldGenerate = false;

    final DefaultFormat defaultFormat = clazz.getAnnotation(DefaultFormat.class);

    ConditionalFormats conditionalFormats = clazz.getAnnotation(ConditionalFormats.class);
    if (conditionalFormats != null) {

        shouldGenerate = true;

        if (defaultFormat == null) {
            throw new IllegalArgumentException(
                    "when using conditionals - you must also speicfy a DefaultFormat annotation");
        }
        ConditionalFormat[] formats = conditionalFormats.value();
        if (formats != null) {
            for (ConditionalFormat conditionalFormat : formats) {
                final ConditionalFormat format = conditionalFormat;
                buldConditionalFormat(format, builder);
            }
        }
    }

    if (defaultFormat != null) {
        shouldGenerate = true;
        buildDefaultFormat(defaultFormat, builder);
    }

    return shouldGenerate;
}

From source file:me.xiaopan.android.gohttp.requestobject.RequestParser.java

/**
 * ????//from  w w w .j av a 2s.c o m
 * @param context 
 * @param requestClass class
 */
public static me.xiaopan.android.gohttp.CacheConfig parseResponseCacheAnnotation(Context context,
        Class<? extends Request> requestClass) {
    me.xiaopan.android.gohttp.requestobject.CacheConfig annotation = requestClass
            .getAnnotation(me.xiaopan.android.gohttp.requestobject.CacheConfig.class);
    if (annotation == null) {
        return null;
    }

    me.xiaopan.android.gohttp.CacheConfig cacheConfig = new me.xiaopan.android.gohttp.CacheConfig();
    cacheConfig.setRefreshCache(annotation.isRefreshCache());
    cacheConfig.setPeriodOfValidity(annotation.periodOfValidity());
    cacheConfig.setRefreshCallback(annotation.isRefreshCallback());
    String cacheDirectory = annotation.cacheDirectory();
    if (cacheDirectory != null && !"".equals(cacheDirectory)) {
        cacheConfig.setCacheDirectory(cacheDirectory);
    } else if (context != null && annotation.cacheDirectoryResId() > 0) {
        cacheConfig.setCacheDirectory(context.getString(annotation.cacheDirectoryResId()));
    }
    return cacheConfig;
}

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

/**
 * ?//from  ww  w. j  av  a 2  s .  c  om
 *
 * @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.cloud.utils.db.SqlGenerator.java

protected static void buildJoins(StringBuilder innerJoin, Class<?> clazz) {
    String tableName = DbUtil.getTableName(clazz);

    SecondaryTable[] sts = DbUtil.getSecondaryTables(clazz);
    ArrayList<String> secondaryTables = new ArrayList<String>();
    for (SecondaryTable st : sts) {
        JoinType jt = clazz.getAnnotation(JoinType.class);
        String join = null;//from   w  w w . j a  v  a  2s.co  m
        if (jt != null) {
            join = jt.type();
        }
        addPrimaryKeyJoinColumns(innerJoin, tableName, st.name(), join, st.pkJoinColumns());
        secondaryTables.add(st.name());
    }

    Class<?> parent = clazz.getSuperclass();
    if (parent.getAnnotation(Entity.class) != null) {
        String table = DbUtil.getTableName(parent);
        PrimaryKeyJoinColumn[] pkjcs = DbUtil.getPrimaryKeyJoinColumns(clazz);
        assert (pkjcs != null) : "No Join columns specified for the super class";
        addPrimaryKeyJoinColumns(innerJoin, tableName, table, null, pkjcs);
    }
}

From source file:controllers.ModuleController.java

private static List<ModuleModel> getNextModules(String input) {
    // get all the supplied view models.
    List<ViewModel> suppliedViewModels = Lists.newArrayList();
    JsonNode inputJson = Json.parse(input);

    // convert json nodes to view models.
    if (inputJson != null && inputJson.isArray()) {
        suppliedViewModels = Lists/*  w  ww .jav  a 2 s  .  c  o  m*/
                .newArrayList(Iterators.transform(inputJson.getElements(), new Function<JsonNode, ViewModel>() {
                    @Override
                    @Nullable
                    public ViewModel apply(@Nullable JsonNode input) {
                        if (!input.isTextual()) {
                            return null;
                        }
                        return createViewModelQuietly(
                                fetchResource(UuidUtils.create(input.asText()), PersistentObject.class), null);

                    }
                }));
    } else if (inputJson != null && inputJson.isObject()) {
        suppliedViewModels.add(createViewModelQuietly(inputJson, null));
    }

    suppliedViewModels = Lists.newArrayList(Iterables.filter(suppliedViewModels, Predicates.notNull()));

    // get all the modules that can use these inputs.
    Map<Module, Double> nullModulesMap = Maps.newHashMap();
    Map<Module, Double> modulesMap = Maps.newHashMap();
    Reflections reflections = new Reflections("controllers.modules", Play.application().classloader());
    for (Class<? extends Module> moduleClass : reflections.getSubTypesOf(Module.class)) {
        // we're not interested in abstract classes.
        if (Modifier.isAbstract(moduleClass.getModifiers())) {
            continue;
        }

        // get the Module.Requires/Requireses annotation for each module class.
        // the requirements within each Module.Require are ANDed.
        // the requirements across multiple Module.Require annotations are ORed.
        List<Module.Requires> requireds = Lists.newArrayList();
        if (moduleClass.isAnnotationPresent(Module.Requires.class)) {
            requireds.add(moduleClass.getAnnotation(Module.Requires.class));
        }
        if (moduleClass.isAnnotationPresent(Module.Requireses.class)) {
            Collections.addAll(requireds, moduleClass.getAnnotation(Module.Requireses.class).value());
        }

        if (requireds.size() == 0) {
            requireds.add(null);
        }

        for (Module.Requires required : requireds) {
            final Set<Class<? extends ViewModel>> requiredViewModelClasses = Sets.newHashSet();
            if (required != null) {
                Collections.addAll(requiredViewModelClasses, required.value());
            }

            // get all the supplied view modules that are relevant to this module.
            List<ViewModel> usefulViewModels = Lists
                    .newArrayList(Iterables.filter(suppliedViewModels, new Predicate<ViewModel>() {
                        @Override
                        public boolean apply(@Nullable ViewModel input) {
                            // if this class is required, then return true.
                            if (requiredViewModelClasses.contains(input.getClass())) {
                                return true;
                            }

                            // if any of its super classes are required, that also works.
                            for (Class<?> superClass : ClassUtils.getAllSuperclasses(input.getClass())) {
                                if (requiredViewModelClasses.contains(superClass)) {
                                    return true;
                                }
                            }

                            return false;
                        }
                    }));

            // if all the requirements were satisfied.
            if (usefulViewModels.size() >= requiredViewModelClasses.size()) {
                // try to create an instance of the module.
                Module module = null;
                try {
                    module = moduleClass.newInstance();
                    module.setViewModels(usefulViewModels);
                } catch (InstantiationException | IllegalAccessException | IllegalArgumentException e) {
                    module = null;
                } finally {
                    // if no module was created, just ignore.
                    if (module == null) {
                        continue;
                    }
                }

                // let's not divide by zero!
                double relevancyScore = suppliedViewModels.size() != 0
                        ? usefulViewModels.size() / (double) suppliedViewModels.size()
                        : 1.0;

                // keep null modules separate.
                Map<Module, Double> targetModulesMap = null;
                if (requiredViewModelClasses.size() > 0) {
                    // if a module of this type does not exist, add it.
                    if (Maps.filterKeys(modulesMap, Predicates.instanceOf(moduleClass)).size() == 0) {
                        targetModulesMap = modulesMap;
                    }
                } else {
                    targetModulesMap = nullModulesMap;
                }
                if (targetModulesMap != null) {
                    targetModulesMap.put(module, relevancyScore);
                }
            }
        }
    }

    // use null modules only if there are no regular ones.
    if (modulesMap.size() == 0) {
        modulesMap = nullModulesMap;
    }

    // convert to view models.
    Set<ModuleModel> moduleViewModels = Sets.newHashSet(
            Iterables.transform(modulesMap.entrySet(), new Function<Entry<Module, Double>, ModuleModel>() {
                @Override
                @Nullable
                public ModuleModel apply(@Nullable Entry<Module, Double> input) {
                    return new ModuleModel(input.getKey()).setRelevancyScore(input.getValue());
                }
            }));

    // order first by relevance and then by name.
    return Ordering.from(new Comparator<ModuleModel>() {
        @Override
        public int compare(ModuleModel o1, ModuleModel o2) {
            int relDiff = (int) Math.round((o2.relevancyScore - o1.relevancyScore) * 1000);
            if (relDiff == 0) {
                return o1.name.compareTo(o2.name);
            }

            return relDiff;
        }
    }).sortedCopy(moduleViewModels);
}

From source file:io.siddhi.doc.gen.core.utils.DocumentationUtils.java

/**
 * Generate extension meta data from the annotated data in the class
 *
 * @param namespaceList  The list of namespaces to which the new extension will be added
 * @param extensionClass Class from which meta data should be extracted from
 * @param logger         The maven plugin logger
 *///from   ww w.  j a v  a2  s. c  o m
private static void addExtensionMetaDataIntoNamespaceList(List<NamespaceMetaData> namespaceList,
        Class<?> extensionClass, Log logger) {
    Extension extensionAnnotation = extensionClass.getAnnotation(Extension.class);

    if (extensionAnnotation != null) { // Discarding extension classes without annotation
        ExtensionMetaData extensionMetaData = new ExtensionMetaData();

        // Finding extension type
        String extensionType = null;
        for (Map.Entry<ExtensionType, Class<?>> entry : ExtensionType.getSuperClassMap().entrySet()) {
            Class<?> superClass = entry.getValue();
            if (superClass.isAssignableFrom(extensionClass) && superClass != extensionClass) {
                extensionType = entry.getKey().getValue();
                break;
            }
        }

        // Discarding the extension if it belongs to an unknown type
        if (extensionType == null) {
            logger.warn("Discarding extension (belonging to an unknown extension type): "
                    + extensionClass.getCanonicalName());
            return;
        }

        extensionMetaData.setName(extensionAnnotation.name());
        extensionMetaData.setDescription(extensionAnnotation.description());

        // Adding query parameters
        ParameterMetaData[] parameters = new ParameterMetaData[extensionAnnotation.parameters().length];
        for (int i = 0; i < extensionAnnotation.parameters().length; i++) {
            Parameter parameterAnnotation = extensionAnnotation.parameters()[i];

            ParameterMetaData parameter = new ParameterMetaData();
            parameter.setName(parameterAnnotation.name());
            parameter.setType(Arrays.asList(parameterAnnotation.type()));
            parameter.setDescription(parameterAnnotation.description());
            parameter.setOptional(parameterAnnotation.optional());
            parameter.setDynamic(parameterAnnotation.dynamic());
            parameter.setDefaultValue(parameterAnnotation.defaultValue());
            parameters[i] = parameter;
        }
        extensionMetaData.setParameters(Arrays.asList(parameters));

        // Adding system parameters
        SystemParameterMetaData[] systemParameters = new SystemParameterMetaData[extensionAnnotation
                .systemParameter().length];
        for (int i = 0; i < extensionAnnotation.systemParameter().length; i++) {
            SystemParameter systemParameterAnnotation = extensionAnnotation.systemParameter()[i];

            SystemParameterMetaData systemParameter = new SystemParameterMetaData();
            systemParameter.setName(systemParameterAnnotation.name());
            systemParameter.setDescription(systemParameterAnnotation.description());
            systemParameter.setDefaultValue(systemParameterAnnotation.defaultValue());
            systemParameter
                    .setPossibleParameters(Arrays.asList(systemParameterAnnotation.possibleParameters()));
            systemParameters[i] = systemParameter;
        }
        extensionMetaData.setSystemParameters(Arrays.asList(systemParameters));

        // Adding return attributes
        ReturnAttributeMetaData[] returnAttributes = new ReturnAttributeMetaData[extensionAnnotation
                .returnAttributes().length];
        for (int i = 0; i < extensionAnnotation.returnAttributes().length; i++) {
            ReturnAttribute parameterAnnotation = extensionAnnotation.returnAttributes()[i];

            ReturnAttributeMetaData returnAttribute = new ReturnAttributeMetaData();
            returnAttribute.setName(parameterAnnotation.name());
            returnAttribute.setType(Arrays.asList(parameterAnnotation.type()));
            returnAttribute.setDescription(parameterAnnotation.description());
            returnAttributes[i] = returnAttribute;
        }
        extensionMetaData.setReturnAttributes(Arrays.asList(returnAttributes));

        // Adding examples
        ExampleMetaData[] examples = new ExampleMetaData[extensionAnnotation.examples().length];
        for (int i = 0; i < extensionAnnotation.examples().length; i++) {
            Example exampleAnnotation = extensionAnnotation.examples()[i];

            ExampleMetaData exampleMetaData = new ExampleMetaData();
            exampleMetaData.setSyntax(exampleAnnotation.syntax());
            exampleMetaData.setDescription(exampleAnnotation.description());
            examples[i] = exampleMetaData;
        }
        extensionMetaData.setExamples(Arrays.asList(examples));

        // Finding the namespace
        String namespaceName = extensionAnnotation.namespace();
        if (Objects.equals(namespaceName, "")) {
            namespaceName = Constants.CORE_NAMESPACE;
        }

        // Finding the relevant namespace in the namespace list
        NamespaceMetaData namespace = null;
        for (NamespaceMetaData existingNamespace : namespaceList) {
            if (Objects.equals(existingNamespace.getName(), namespaceName)) {
                namespace = existingNamespace;
                break;
            }
        }
        // Creating namespace if it doesn't exist
        if (namespace == null) {
            namespace = new NamespaceMetaData();
            namespace.setName(namespaceName);
            namespace.setExtensionMap(new TreeMap<>());
            namespaceList.add(namespace);
        }

        // Adding to the relevant extension metadata list in the namespace
        List<ExtensionMetaData> extensionMetaDataList = namespace.getExtensionMap()
                .computeIfAbsent(extensionType, k -> new ArrayList<>());

        extensionMetaDataList.add(extensionMetaData);
    }
}

From source file:dk.netarkivet.archive.webinterface.BatchGUI.java

/**
 * Retrieves the HTML code for the description of the class. The description of the class is given in the resource
 * annotation which has the type of the given class.
 * <p>/*from   w ww .j  a v  a 2  s  . c o  m*/
 * <br/>
 * E.g. <br/>
 *
 * @param c The class to be described.
 * @param locale The locale language package.
 * @return The HTML code describing the class.
 * @Resource(description="Batchjob for finding URLs which matches a given" +
 * " regular expression and has a mimetype which matches another" + " regular expression.",
 * type=dk.netarkivet.common.utils.batch.UrlSearch.class)}
 * <p>
 * <br/>
 * <br/>
 * Which gives the UrlSearch batchjob the following description: <br/>
 * <br/>
 * Description: Batchjob for finding URLs which matches a given regular expression and has a mimetype which matches
 * another regular expression. &lt;br/&gt;&lt;br/&gt;
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
private static String getClassDescription(Class c, Locale locale) {
    // retrieve the resources.
    Resources r = (Resources) c.getAnnotation(Resources.class);
    if (r == null) {
        return "<br/>\n";
    }

    // Find and return the description of this class (if any).
    for (Resource resource : r.value()) {
        if (resource.type().getName().equals(c.getName())) {
            return I18N.getString(locale, "batchpage;Description", new Object[] {}) + ": "
                    + resource.description() + "<br/><br/>\n";
        }
    }

    // no description found, then return empty string.
    return "<br/>\n";
}

From source file:com.github.dactiv.common.utils.ReflectionUtils.java

/**
 * ?/*from  www  .ja v  a 2 s  .  co  m*/
 * 
 * @param targetClass
 *            Class
 * @param annotationClass
 *            Class
 * 
 * @return Object
 */
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);
    }

    return null;
}