Example usage for java.lang Class isAnnotation

List of usage examples for java.lang Class isAnnotation

Introduction

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

Prototype

public boolean isAnnotation() 

Source Link

Document

Returns true if this Class object represents an annotation type.

Usage

From source file:net.ymate.platform.commons.util.ClassUtils.java

/**
 * ?.class??'$'??Java"com/ymatesoft/common/A.class"~"com.ymatesoft.common.A"
 * /*from w w w .  ja v a  2s . c o  m*/
 * @param collections
 * @param clazz
 * @param packageName
 * @param packageFile
 * @param callingClass
 */
@SuppressWarnings("unchecked")
protected static <T> void __doFindClassByClazz(Collection<Class<T>> collections, Class<T> clazz,
        String packageName, File packageFile, Class<?> callingClass) {
    if (packageFile.isFile()) {
        try {
            if (packageFile.getName().endsWith(".class") && packageFile.getName().indexOf('$') < 0) {
                Class<?> _class = ResourceUtils.loadClass(
                        packageName + "." + packageFile.getName().replace(".class", ""), callingClass);
                if (_class != null) {
                    if (clazz.isAnnotation()) {
                        if (isAnnotationOf(_class, (Class<Annotation>) clazz)) {
                            collections.add((Class<T>) _class);
                        }
                    } else if (clazz.isInterface()) {
                        if (isInterfaceOf(_class, clazz)) {
                            collections.add((Class<T>) _class);
                        }
                    } else if (isSubclassOf(_class, clazz)) {
                        collections.add((Class<T>) _class);
                    }
                }
            }
        } catch (NoClassDefFoundError e) {
            _LOG.warn("", RuntimeUtils.unwrapThrow(e));
        } catch (ClassNotFoundException e) {
            _LOG.warn("", RuntimeUtils.unwrapThrow(e));
        }
    } else {
        File[] _tmpfiles = packageFile.listFiles();
        for (File _tmpFile : _tmpfiles != null ? _tmpfiles : new File[0]) {
            __doFindClassByClazz(collections, clazz, packageName + "." + packageFile.getName(), _tmpFile,
                    callingClass);
        }
    }
}

From source file:net.ymate.platform.commons.util.ClassUtils.java

/**
 * ? Jar .class??'$'??Java"com/ymatesoft/common/A.class"~"com.ymatesoft.common.A"
 * /*from   ww w  .j av a  2s  .c om*/
 * @param collections
 * @param clazz
 * @param packageName
 * @param jarFile
 * @param callingClass
 */
@SuppressWarnings("unchecked")
protected static <T> void __doFindClassByJar(Collection<Class<T>> collections, Class<T> clazz,
        String packageName, JarFile jarFile, Class<?> callingClass) {
    Enumeration<JarEntry> _entriesEnum = jarFile.entries();
    for (; _entriesEnum.hasMoreElements();) {
        JarEntry _entry = _entriesEnum.nextElement();
        // ??? '/'  '.'?.class???'$'??
        String _className = _entry.getName().replaceAll("/", ".");
        if (_className.endsWith(".class") && _className.indexOf('$') < 0) {
            if (_className.startsWith(packageName)) {
                Class<?> _class = null;
                try {
                    _class = ResourceUtils.loadClass(_className.substring(0, _className.lastIndexOf('.')),
                            callingClass);
                    if (_class != null) {
                        if (clazz.isAnnotation()) {
                            if (isAnnotationOf(_class, (Class<Annotation>) clazz)) {
                                collections.add((Class<T>) _class);
                            }
                        } else if (clazz.isInterface()) {
                            if (isInterfaceOf(_class, clazz)) {
                                collections.add((Class<T>) _class);
                            }
                        } else if (isSubclassOf(_class, clazz)) {
                            collections.add((Class<T>) _class);
                        }
                    }
                } catch (NoClassDefFoundError e) {
                    _LOG.warn("", RuntimeUtils.unwrapThrow(e));
                } catch (ClassNotFoundException e) {
                    _LOG.warn("", RuntimeUtils.unwrapThrow(e));
                }
            }
        }
    }
}

From source file:net.ymate.platform.core.beans.impl.DefaultBeanFactory.java

@SuppressWarnings("unchecked")
public <T> T getBean(Class<T> clazz) {
    T _obj = null;//from ww  w .jav  a  2  s  . co m
    if (clazz != null && !clazz.isAnnotation()) {
        BeanMeta _beanMeta = null;
        if (clazz.isInterface()) {
            Class<?> _targetClass = this.__beanInterfacesMap.get(clazz);
            _beanMeta = this.__beanInstancesMap.get(_targetClass);
        } else {
            _beanMeta = this.__beanInstancesMap.get(clazz);
        }
        if (_beanMeta != null) {
            if (!_beanMeta.isSingleton()) {
                try {
                    _obj = (T) _beanMeta.getBeanClass().newInstance();
                    if (__proxyFactory != null) {
                        _obj = (T) __wrapProxy(__proxyFactory, _obj);
                    }
                    __initBeanIoC(_beanMeta.getBeanClass(), _obj);
                } catch (Exception e) {
                    _LOG.warn("", e);
                }
            } else {
                _obj = (T) _beanMeta.getBeanObject();
            }
        }
        if (_obj == null && this.__parentFactory != null) {
            _obj = this.__parentFactory.getBean(clazz);
        }
    }
    return _obj;
}

From source file:net.ymate.platform.core.beans.impl.DefaultBeanFactory.java

public void init() throws Exception {
    if (this.__beanLoader == null) {
        if (this.__parentFactory != null) {
            this.__beanLoader = this.__parentFactory.getLoader();
        }//from  w w  w  .  j a va2  s .  c om
        if (this.__beanLoader == null) {
            this.__beanLoader = new DefaultBeanLoader();
        }
    }
    if (!__packageNames.isEmpty())
        for (String _packageName : __packageNames) {
            List<Class<?>> _classes = this.__beanLoader.load(_packageName);
            for (Class<?> _class : _classes) {
                // ?????
                if (!_class.isAnnotation() && !_class.isEnum() && !_class.isInterface()) {
                    Annotation[] _annotations = _class.getAnnotations();
                    if (_annotations != null && _annotations.length > 0) {
                        for (Annotation _anno : _annotations) {
                            IBeanHandler _handler = __beanHandlerMap.get(_anno.annotationType());
                            if (_handler != null) {
                                Object _instance = _handler.handle(_class);
                                if (_instance != null) {
                                    if (_instance instanceof BeanMeta) {
                                        __addClass((BeanMeta) _instance);
                                    } else {
                                        __addClass(BeanMeta.create(_instance, _class));
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
}

From source file:net.ymate.platform.plugin.impl.DefaultPluginFactory.java

@SuppressWarnings("unchecked")
private List<Class<? extends IBeanHandler>> __doLoadBeanHandles() throws Exception {
    List<Class<? extends IBeanHandler>> _returnValues = new ArrayList<Class<? extends IBeanHandler>>();
    IBeanLoader _loader = new DefaultBeanLoader();
    ////from   www . j ava2  s  .  c om
    IBeanFilter _beanFilter = new IBeanFilter() {
        public boolean filter(Class<?> targetClass) {
            return !(targetClass.isInterface() || targetClass.isAnnotation() || targetClass.isEnum())
                    && (targetClass.isAnnotationPresent(Handler.class)
                            && ClassUtils.isInterfaceOf(targetClass, IBeanHandler.class));
        }
    };
    //
    for (String _package : __config.getAutoscanPackages()) {
        for (Class<?> _targetClass : _loader.load(_package, _beanFilter)) {
            _returnValues.add((Class<? extends IBeanHandler>) _targetClass);
        }
    }
    return _returnValues;
}

From source file:org.amplafi.flow.flowproperty.FixedFlowPropertyValueProvider.java

public FixedFlowPropertyValueProvider(Class<?> defaultClass) {
    ApplicationIllegalArgumentException.notNull(defaultClass, "Fixed defaultClass cannot be null.");
    ApplicationIllegalArgumentException.valid(
            !defaultClass.isAnnotation() && !defaultClass.isInterface() && !defaultClass.isPrimitive(),
            defaultClass, ": cannot be instantiated.");
    this.defaultObject = null;
    this.defaultClass = defaultClass;
}

From source file:org.amplafi.flow.flowproperty.FixedFlowPropertyValueProvider.java

@SuppressWarnings("unchecked")
public static <FPP extends FlowPropertyProvider> FixedFlowPropertyValueProvider newFixedFlowPropertyValueProvider(
        Class<?> defaultClass, FlowPropertyDefinitionImplementor flowPropertyDefinition,
        boolean testAndConfigFlowPropertyDefinition) {
    FixedFlowPropertyValueProvider fixedFlowPropertyValueProvider = null;

    ApplicationIllegalArgumentException.valid(!defaultClass.isAnnotation(), defaultClass,
            "is an annotation. Annotations cannot be instatiated.");
    if (defaultClass == int.class) {
        return newFixedFlowPropertyValueProvider(Integer.valueOf(0), flowPropertyDefinition,
                testAndConfigFlowPropertyDefinition);
    } else if (defaultClass == long.class) {
        return newFixedFlowPropertyValueProvider(Long.valueOf(0), flowPropertyDefinition,
                testAndConfigFlowPropertyDefinition);
    } else if (defaultClass == boolean.class) {
        return newFixedFlowPropertyValueProvider(Boolean.valueOf(false), flowPropertyDefinition,
                testAndConfigFlowPropertyDefinition);
    } else if (defaultClass.isEnum()) {
        // use the first enum as the default.
        return newFixedFlowPropertyValueProvider(((Class<Enum<?>>) defaultClass).getEnumConstants()[0],
                flowPropertyDefinition, testAndConfigFlowPropertyDefinition);
    }//from  w w  w . j ava  2s  . co m
    Class<?> classToCreate;
    if (defaultClass == Set.class) {
        classToCreate = LinkedHashSet.class;
    } else if (defaultClass == List.class) {
        classToCreate = ArrayList.class;
    } else if (defaultClass == Map.class) {
        classToCreate = HashMap.class;
    } else {
        classToCreate = defaultClass;
    }
    fixedFlowPropertyValueProvider = new FixedFlowPropertyValueProvider(classToCreate);

    fixedFlowPropertyValueProvider.convertable(flowPropertyDefinition);
    if (testAndConfigFlowPropertyDefinition) {
        DataClassDefinition dataClassDefinition = flowPropertyDefinition.getDataClassDefinition();
        if (dataClassDefinition.isDataClassDefined()) {
            ApplicationIllegalArgumentException.valid(dataClassDefinition.isAssignableFrom(defaultClass),
                    dataClassDefinition, " cannot be assigned ");
        } else {
            dataClassDefinition.setDataClass(defaultClass);
        }
    }
    return fixedFlowPropertyValueProvider;
}

From source file:org.amplafi.hivemind.factory.servicessetter.ServicesSetterImpl.java

/**
 * @param propertyType//from   w  ww . ja  v  a  2  s  .co m
 * @return true class can be wired up as a service
 */
@Override
public boolean isWireableClass(Class<?> propertyType) {
    if (
    // exclude primitives or other things that are not mockable in any form
    propertyType.isPrimitive() || propertyType.isAnnotation() || propertyType.isArray() || propertyType.isEnum()
    // generated classes
            || propertyType.getCanonicalName() == null
            // exclude java classes
            || propertyType.getPackage().getName().startsWith("java")) {
        return false;
    } else {
        // exclude things that are explicitly labeled as not being injectable
        NotService notService = propertyType.getAnnotation(NotService.class);
        return notService == null;
    }
}

From source file:org.apache.bval.jsr.xml.ValidationMappingParser.java

@SuppressWarnings("unchecked")
private void processConstraintDefinitions(List<ConstraintDefinitionType> constraintDefinitionList,
        String defaultPackage) {//from  w  w  w  . j  a  v  a  2s  .c o m
    for (ConstraintDefinitionType constraintDefinition : constraintDefinitionList) {
        String annotationClassName = constraintDefinition.getAnnotation();

        Class<?> clazz = loadClass(annotationClassName, defaultPackage);
        if (!clazz.isAnnotation()) {
            throw new ValidationException(annotationClassName + " is not an annotation");
        }
        Class<? extends Annotation> annotationClass = (Class<? extends Annotation>) clazz;

        ValidatedByType validatedByType = constraintDefinition.getValidatedBy();
        List<Class<? extends ConstraintValidator<?, ?>>> classes = new ArrayList<Class<? extends ConstraintValidator<?, ?>>>();
        /*
         If include-existing-validator is set to false,
         ConstraintValidator defined on the constraint annotation are ignored.
          */
        if (validatedByType.getIncludeExistingValidators() != null
                && validatedByType.getIncludeExistingValidators()) {
            /*
             If set to true, the list of ConstraintValidators described in XML
             are concatenated to the list of ConstraintValidator described on the
             annotation to form a new array of ConstraintValidator evaluated.
             */
            classes.addAll(findConstraintValidatorClasses(annotationClass));
        }
        for (String validatorClassName : validatedByType.getValue()) {
            Class<? extends ConstraintValidator<?, ?>> validatorClass;
            validatorClass = (Class<? extends ConstraintValidator<?, ?>>) loadClass(validatorClassName);

            if (!ConstraintValidator.class.isAssignableFrom(validatorClass)) {
                throw new ValidationException(validatorClass + " is not a constraint validator class");
            }

            /*
            Annotation based ConstraintValidator come before XML based
            ConstraintValidator in the array. The new list is returned
            by ConstraintDescriptor.getConstraintValidatorClasses().
             */
            if (!classes.contains(validatorClass))
                classes.add(validatorClass);
        }
        if (factory.getConstraintsCache().containsConstraintValidator(annotationClass)) {
            throw new ValidationException(
                    "Constraint validator for " + annotationClass.getName() + " already configured.");
        } else {
            factory.getConstraintsCache().putConstraintValidator(annotationClass,
                    classes.toArray(new Class[classes.size()]));
        }
    }
}

From source file:org.apache.sling.contextaware.config.impl.metadata.AnnotationClassParser.java

/**
 * Checks if the given class is suitable to be mapped with context-aware configuration.
 * The given class has to be an annotation class, and the {@link Configuration} annotation has to be present.
 * @param clazz Given class/*  w  w  w .j  a  v  a2  s . c o  m*/
 * @return True if class is suitable for context-aware configuration
 */
public static boolean isContextAwareConfig(Class<?> clazz) {
    return clazz.isAnnotation() && clazz.isAnnotationPresent(Configuration.class);
}