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: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//from w  w w.  j av  a2 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:com.actionbarsherlock.ActionBarSherlock.java

/**
 * Register an ActionBarSherlock implementation.
 *
 * @param implementationClass Target implementation class which extends
 * {@link ActionBarSherlock}. This class must also be annotated with
 * {@link Implementation}./* w  w  w.  j  ava  2 s. co  m*/
 */
public static void registerImplementation(Class<? extends ActionBarSherlock> implementationClass) {
    if (!implementationClass.isAnnotationPresent(Implementation.class)) {
        throw new IllegalArgumentException(
                "Class " + implementationClass.getSimpleName() + " is not annotated with @Implementation");
    } else if (IMPLEMENTATIONS.containsValue(implementationClass)) {
        if (DEBUG)
            Log.w(TAG, "Class " + implementationClass.getSimpleName() + " already registered");
        return;
    }

    Implementation impl = implementationClass.getAnnotation(Implementation.class);
    if (DEBUG)
        Log.i(TAG, "Registering " + implementationClass.getSimpleName() + " with qualifier " + impl);
    IMPLEMENTATIONS.put(impl, implementationClass);
}

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

protected static void parseClassForAttributes(GuzzContextImpl gf, POJOBasedObjectMapping map, Business business,
        DBGroup dbGroup, SimpleTable st, Class domainClass) {
    //???//  ww w .  j a v a  2s  .co m
    Class parentCls = domainClass.getSuperclass();
    if (parentCls != null && parentCls.isAnnotationPresent(MappedSuperclass.class)) {
        parseClassForAttributes(gf, map, business, dbGroup, st, parentCls);
    }

    javax.persistence.Access access = (javax.persistence.Access) domainClass
            .getAnnotation(javax.persistence.Access.class);
    AccessType accessType = null;

    if (access == null) {
        //@Id@Idfieldproperty
        boolean hasColumnAOnField = false;
        boolean hasColumnAOnProperty = false;

        //detect from @Id, field first.
        Field[] fs = domainClass.getDeclaredFields();

        for (Field f : fs) {
            if (f.isAnnotationPresent(Transient.class))
                continue;
            if (f.isAnnotationPresent(javax.persistence.Id.class)) {
                accessType = AccessType.FIELD;
                break;
            } else if (f.isAnnotationPresent(javax.persistence.Column.class)) {
                hasColumnAOnField = true;
            } else if (f.isAnnotationPresent(org.guzz.annotations.Column.class)) {
                hasColumnAOnField = true;
            }
        }

        if (accessType == null) {
            Method[] ms = domainClass.getDeclaredMethods();
            for (Method m : ms) {
                if (m.isAnnotationPresent(Transient.class))
                    continue;
                if (m.isAnnotationPresent(javax.persistence.Id.class)) {
                    accessType = AccessType.PROPERTY;
                    break;
                } else if (m.isAnnotationPresent(javax.persistence.Column.class)) {
                    hasColumnAOnProperty = true;
                } else if (m.isAnnotationPresent(org.guzz.annotations.Column.class)) {
                    hasColumnAOnProperty = true;
                }
            }
        }

        //@Id@Column@Columnfield?
        if (accessType == null) {
            if (hasColumnAOnField) {
                accessType = AccessType.FIELD;
            } else if (hasColumnAOnProperty) {
                accessType = AccessType.PROPERTY;
            } else {
                accessType = AccessType.FIELD;
            }
        }
    } else {
        accessType = access.value();
    }

    //orm by field
    if (accessType == AccessType.FIELD) {
        Field[] fs = domainClass.getDeclaredFields();

        for (Field f : fs) {
            if (f.isAnnotationPresent(Transient.class))
                continue;
            if (Modifier.isTransient(f.getModifiers()))
                continue;
            if (Modifier.isStatic(f.getModifiers()))
                continue;

            if (f.isAnnotationPresent(javax.persistence.Id.class)) {
                addIdMapping(gf, map, st, dbGroup, f.getName(), domainClass, f);
            } else {
                addPropertyMapping(gf, map, st, f.getName(), f, f.getType());
            }
        }
    } else {
        Method[] ms = domainClass.getDeclaredMethods();
        for (Method m : ms) {
            if (m.isAnnotationPresent(Transient.class))
                continue;
            if (Modifier.isTransient(m.getModifiers()))
                continue;
            if (Modifier.isStatic(m.getModifiers()))
                continue;
            if (Modifier.isPrivate(m.getModifiers()))
                continue;

            String methodName = m.getName();
            String fieldName = null;

            if (m.getParameterTypes().length != 0) {
                continue;
            } else if (Void.TYPE.equals(m.getReturnType())) {
                continue;
            }

            if (methodName.startsWith("get")) {
                fieldName = methodName.substring(3);
            } else if (methodName.startsWith("is")) {//is boolean?
                Class retType = m.getReturnType();

                if (boolean.class.isAssignableFrom(retType)) {
                    fieldName = methodName.substring(2);
                } else if (Boolean.class.isAssignableFrom(retType)) {
                    fieldName = methodName.substring(2);
                }
            }

            //not a javabean read method
            if (fieldName == null) {
                continue;
            }

            fieldName = java.beans.Introspector.decapitalize(fieldName);

            if (m.isAnnotationPresent(javax.persistence.Id.class)) {
                addIdMapping(gf, map, st, dbGroup, fieldName, domainClass, m);
            } else {
                addPropertyMapping(gf, map, st, fieldName, m, m.getReturnType());
            }
        }
    }

    //?attribute override
    AttributeOverride gao = (AttributeOverride) domainClass.getAnnotation(AttributeOverride.class);
    AttributeOverrides gaos = (AttributeOverrides) domainClass.getAnnotation(AttributeOverrides.class);
    AttributeOverride[] aos = gao == null ? new AttributeOverride[0] : new AttributeOverride[] { gao };
    if (gaos != null) {
        ArrayUtil.addToArray(aos, gaos.value());
    }

    for (AttributeOverride ao : aos) {
        String name = ao.name();
        Column col = ao.column();

        TableColumn tc = st.getColumnByPropName(name);
        Assert.assertNotNull(tc,
                "@AttributeOverride cann't override a attribute that doesn't exist. The attribute is:" + name);

        //update is remove and add
        st.removeColumn(tc);

        //change the column name in the database.
        tc.setColName(col.name());

        st.addColumn(tc);
    }
}

From source file:me.anon.lib.Views.java

private static void inject(final Object target, Object source, Finder finder) {
    if (target.getClass().getDeclaredFields() != null) {
        ArrayList<Method> methods = new ArrayList<Method>();
        ArrayList<Field> fields = new ArrayList<Field>();
        Class objOrSuper = target.getClass();

        if (!objOrSuper.isAnnotationPresent(Injectable.class)) {
            Log.e("InjectView", "No Injectable annotation for class " + objOrSuper);
            return;
        }//from  w  w  w.j  av  a2s  . c o m

        while (objOrSuper.isAnnotationPresent(Injectable.class)) {
            for (Field field : objOrSuper.getDeclaredFields()) {
                if (field.isAnnotationPresent(InjectView.class) || field.isAnnotationPresent(InjectViews.class)
                        || field.isAnnotationPresent(InjectFragment.class)
                        || field.isAnnotationPresent(OnClick.class)) {
                    fields.add(field);
                }
            }

            for (Method method : objOrSuper.getDeclaredMethods()) {
                if (method.isAnnotationPresent(OnClick.class)) {
                    methods.add(method);
                }
            }

            objOrSuper = objOrSuper.getSuperclass();
        }

        for (Field field : fields) {
            if (field.isAnnotationPresent(InjectView.class)) {
                InjectView a = (InjectView) field.getAnnotation(InjectView.class);

                try {
                    field.setAccessible(true);

                    int id = ((InjectView) a).value();
                    if (id < 1) {
                        String key = ((InjectView) a).id();
                        if (TextUtils.isEmpty(key)) {
                            key = field.getName();
                            key = key.replaceAll("(.)([A-Z])", "$1_$2").toLowerCase(Locale.ENGLISH);
                        }

                        Field idField = R.id.class.getField(key);
                        id = idField.getInt(null);
                    }

                    View v = finder.findById(source, id);

                    if (v != null) {
                        field.set(target, v);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else if (field.isAnnotationPresent(InjectViews.class)) {
                try {
                    InjectViews annotation = (InjectViews) field.getAnnotation(InjectViews.class);
                    field.setAccessible(true);

                    int[] ids = annotation.value();
                    String[] strIds = annotation.id();
                    Class[] instances = annotation.instances();

                    List<View> views = new ArrayList<View>(ids.length);

                    if (ids.length > 0) {
                        for (int index = 0; index < ids.length; index++) {
                            View v = finder.findById(source, ids[index]);
                            views.add(index, v);
                        }
                    } else if (strIds.length > 0) {
                        for (int index = 0; index < ids.length; index++) {
                            String key = annotation.id()[index];
                            Field idField = R.id.class.getField(key);
                            int id = idField.getInt(null);

                            View v = finder.findById(source, id);
                            views.add(index, v);
                        }
                    } else if (instances.length > 0) {
                        for (int index = 0; index < instances.length; index++) {
                            List<View> v = finder.findByInstance(source, instances[index]);
                            views.addAll(v);
                        }
                    }

                    field.set(target, views);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else if (field.isAnnotationPresent(InjectFragment.class)) {
                InjectFragment annotation = (InjectFragment) field.getAnnotation(InjectFragment.class);

                try {
                    field.setAccessible(true);

                    int id = ((InjectFragment) annotation).value();
                    Object fragment = null;

                    if (id < 1) {
                        String tag = ((InjectFragment) annotation).tag();

                        fragment = finder.findFragmentByTag(source, tag);
                    } else {
                        fragment = finder.findFragmentById(source, id);
                    }

                    if (fragment != null) {
                        field.set(target, fragment);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            if (field.isAnnotationPresent(OnClick.class)) {
                OnClick annotation = (OnClick) field.getAnnotation(OnClick.class);

                try {
                    if (field.get(target) != null) {
                        final View view = ((View) field.get(target));

                        if (!TextUtils.isEmpty(annotation.method())) {
                            final String clickName = annotation.method();
                            view.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    try {
                                        Class<?> c = Class.forName(target.getClass().getCanonicalName());
                                        Method m = c.getMethod(clickName, View.class);
                                        m.invoke(target, v);
                                    } catch (Exception e) {
                                        throw new IllegalArgumentException("Method not found " + clickName);
                                    }
                                }
                            });
                        } else {
                            view.setOnClickListener((View.OnClickListener) target);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        for (final Method method : methods) {
            if (method.isAnnotationPresent(OnClick.class)) {
                final OnClick annotation = (OnClick) method.getAnnotation(OnClick.class);
                final String clickName = method.getName();

                try {
                    int id = annotation.value();
                    if (id < 1) {
                        String key = annotation.id();

                        if (TextUtils.isEmpty(key)) {
                            key = clickName;
                            key = key.replaceAll("^(on)?(.*)Click$", "$2");
                            key = key.replaceAll("(.)([A-Z])", "$1_$2").toLowerCase(Locale.ENGLISH);
                        }

                        Field field = R.id.class.getField(key);
                        id = field.getInt(null);
                    }

                    View view = finder.findById(source, id);
                    view.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            try {
                                if (method != null && method.getParameterTypes().length > 0) {
                                    Class<?> paramType = method.getParameterTypes()[0];
                                    method.setAccessible(true);
                                    method.invoke(target, paramType.cast(v));
                                } else if (method != null && method.getParameterTypes().length < 1) {
                                    method.setAccessible(true);
                                    method.invoke(target);
                                } else {
                                    new IllegalArgumentException(
                                            "Failed to find method " + clickName + " with nil or View params")
                                                    .printStackTrace();
                                }
                            } catch (InvocationTargetException e) {
                                e.printStackTrace();
                            } catch (IllegalAccessException e) {
                                e.printStackTrace();
                            }
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

From source file:org.squidy.manager.scanner.PackageScanner.java

/**
 * @param <T>/*from   w w w.  ja va  2  s  .  co  m*/
 * @param annotationType
 * @return
 */
public static <T> Class<T>[] findAllClassesWithAnnotation(Class<? extends Annotation> annotationType)
        throws SquidyException {

    List<String> foundClassNames = new ArrayList<String>();

    String packagePrefix = "org.squidy";

    String thePackagePattern = packagePrefix.replace('.', '/') + "/[/\\w]*\\.class";
    String classPath = System.getProperty("sun.boot.class.path") + System.getProperty("path.separator", ";")
            + System.getProperty("java.class.path");

    URL[] classPathUrls = getClasspathUrls(classPath);

    for (URL url : classPathUrls) {
        File resource = urlToFile(url);

        // if (System.getProperty("os.name").contains("Windows") &&
        // resource.startsWith("/")) {
        // resource = resource.substring(1, resource.length());
        // }

        // resource = resource.replace('/', File.separatorChar);

        if (resource.getName().endsWith(".jar")) {
            foundClassNames.addAll(findAllClassesInJarContainedBy(thePackagePattern, resource));
        } else { // Url is Directory
            findAllClassesInDirectoryContainedBy0(foundClassNames, packagePrefix, resource);
        }
    }

    List<Class<T>> types = new ArrayList<Class<T>>();

    for (String className : foundClassNames) {
        try {

            Class<T> type = null;
            try {
                type = (Class<T>) PackageScanner.class.getClassLoader().loadClass(className);
            } catch (Exception e) {

                //               if (LOG.isErrorEnabled()) {
                //                  LOG.error("Could not load class on first sight: " + e.getMessage());
                //               }

                type = (Class<T>) PackageScanner.class.getClassLoader().loadClass(className);
            }

            if (type.isAnnotationPresent(annotationType)) {
                types.add(type);
            }
        } catch (ClassNotFoundException e) {
            //            throw new SquidyException(e);
            if (LOG.isErrorEnabled()) {
                LOG.error("Could not load class " + e.getMessage(), e);
            }
        }
    }

    return types.toArray(new Class[types.size()]);
}

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

/**
 * ?//  w ww  .  j av  a2s.c  o  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;
}

From source file:adalid.core.XS1.java

static Class<?> getAnnotatedClass(Class<?> clazz, Class<? extends Annotation> annotationClass) {
    if (clazz == null || annotationClass == null) {
        return null;
    }// w ww. j av a2s. c  o m
    if (clazz.isAnnotationPresent(annotationClass)) {
        return clazz;
    }
    return getAnnotatedClass(clazz.getSuperclass(), annotationClass);
}

From source file:com.github.spring.mvc.util.handler.UriMatchingStaticMethodMatcherPointcut.java

@Override
public boolean matches(Method method, Class<?> targetClass) {
    return targetClass.isAnnotationPresent(Includes.class) || targetClass.isAnnotationPresent(Excludes.class);
}

From source file:org.ext4spring.parameter.aop.ParameterJavaBeanPointcut.java

@Override
public boolean matches(Method method, Class<?> clazz) {
    if (clazz.isAnnotationPresent(ParameterBean.class) && (method.getName().startsWith("get")
            || method.getName().startsWith("is") || method.getName().startsWith("set"))) {
        return true;
    }/*from w ww.  j a  v a  2  s  .  com*/
    return false;
}

From source file:net.sf.firemox.xml.XmlConfiguration.java

/**
 * Return the method name corresponding to the specified TAG.
 * //from   ww  w. j  a va2s  . c om
 * @param tagName
 * @return the method name corresponding to the specified TAG.
 */
static XmlToMDB getXmlClass(String tagName, Map<String, XmlToMDB> instances, Class<?> nameSpaceCall) {
    if (!nameSpaceCall.getSimpleName().startsWith("Xml"))
        throw new InternalError("Caller should be an Xml class : " + nameSpaceCall);

    XmlToMDB nodeClass = instances.get(tagName);
    if (nodeClass != null) {
        return nodeClass;
    }

    String simpleClassName = StringUtils.capitalize(tagName.replaceAll("-", ""));
    String packageName = nameSpaceCall.getPackage().getName();
    String namespace = nameSpaceCall.getSimpleName().substring(3).toLowerCase();
    String className = packageName + "." + namespace + "." + simpleClassName;
    XmlToMDB result;
    try {
        result = (XmlToMDB) Class.forName(className).newInstance();
    } catch (Throwable e) {
        Class<?> mdbClass = null;
        simpleClassName = WordUtils.capitalize(tagName.replaceAll("-", " ")).replaceAll(" ", "");
        try {
            result = (XmlToMDB) Class.forName(packageName + "." + namespace + "." + simpleClassName)
                    .newInstance();
        } catch (Throwable e1) {
            try {
                className = StringUtils.chomp(packageName, ".xml") + "." + namespace + "." + simpleClassName;
                mdbClass = Class.forName(className);
                if (!mdbClass.isAnnotationPresent(XmlTestElement.class)) {
                    result = (XmlToMDB) mdbClass.newInstance();
                } else {
                    result = getAnnotedBuilder(mdbClass, tagName, packageName, namespace);
                }
            } catch (Throwable ei2) {
                error("Unsupported " + namespace + " '" + tagName + "'");
                result = DummyBuilder.instance();
            }
        }
    }
    instances.put(tagName, result);
    return result;
}