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:com.discovery.darchrow.lang.ClassUtil.java

/**
 *  class info map for LOGGER.//from  w  w  w  .j  a  v  a2  s.  c  o  m
 *
 * @param klass
 *            the clz
 * @return the map for log
 */
public static Map<String, Object> getClassInfoMapForLog(Class<?> klass) {
    if (Validator.isNullOrEmpty(klass)) {
        return null;
    }

    Map<String, Object> map = new LinkedHashMap<String, Object>();

    map.put("clz.getCanonicalName()", klass.getCanonicalName());//"com.feilong.core.date.DatePattern"
    map.put("clz.getName()", klass.getName());//"com.feilong.core.date.DatePattern"
    map.put("clz.getSimpleName()", klass.getSimpleName());//"DatePattern"

    map.put("clz.getComponentType()", klass.getComponentType());
    // ?? voidboolean?byte?char?short?int?long?float  double?
    map.put("clz.isPrimitive()", klass.isPrimitive());

    // ??,
    map.put("clz.isLocalClass()", klass.isLocalClass());
    // ????,??????
    map.put("clz.isMemberClass()", klass.isMemberClass());

    //isSynthetic()?Class????java??false?trueJVM???java??????
    map.put("clz.isSynthetic()", klass.isSynthetic());
    map.put("clz.isArray()", klass.isArray());
    map.put("clz.isAnnotation()", klass.isAnnotation());

    //??true
    map.put("clz.isAnonymousClass()", klass.isAnonymousClass());
    map.put("clz.isEnum()", klass.isEnum());

    return map;
}

From source file:cn.teamlab.wg.framework.struts2.json.PackageBasedActionConfigBuilder.java

/**
 * Interfaces, enums, annotations, and abstract classes cannot be
 * instantiated./*from   w  w  w.  ja v a  2  s .co  m*/
 * 
 * @param actionClass
 *            class to check
 * @return returns true if the class cannot be instantiated or should be
 *         ignored
 */
protected boolean cannotInstantiate(Class<?> actionClass) {
    return actionClass.isAnnotation() || actionClass.isInterface() || actionClass.isEnum()
            || (actionClass.getModifiers() & Modifier.ABSTRACT) != 0 || actionClass.isAnonymousClass();
}

From source file:com.espertech.esper.epl.core.EngineImportServiceImpl.java

/**
 * Finds a class by class name using the auto-import information provided.
 * @param className is the class name to find
 * @return class/*ww w .ja v a2s  . c o m*/
 * @throws ClassNotFoundException if the class cannot be loaded
 */
protected Class resolveClassInternal(String className, boolean requireAnnotation)
        throws ClassNotFoundException {
    // Attempt to retrieve the class with the name as-is
    try {
        ClassLoader cl = Thread.currentThread().getContextClassLoader();
        return Class.forName(className, true, cl);
    } catch (ClassNotFoundException e) {
        if (log.isDebugEnabled()) {
            log.debug("Class not found for resolving from name as-is '" + className + "'");
        }
    }

    // Try all the imports
    for (String importName : imports) {
        boolean isClassName = isClassName(importName);
        boolean containsPackage = importName.indexOf('.') != -1;
        String classNameWithDot = "." + className;
        String classNameWithDollar = "$" + className;

        // Import is a class name
        if (isClassName) {
            if ((containsPackage && importName.endsWith(classNameWithDot))
                    || (containsPackage && importName.endsWith(classNameWithDollar))
                    || (!containsPackage && importName.equals(className))
                    || (!containsPackage && importName.endsWith(classNameWithDollar))) {
                ClassLoader cl = Thread.currentThread().getContextClassLoader();
                return Class.forName(importName, true, cl);
            }

            String prefixedClassName = importName + '$' + className;
            try {
                ClassLoader cl = Thread.currentThread().getContextClassLoader();
                Class clazz = Class.forName(prefixedClassName, true, cl);
                if (!requireAnnotation || clazz.isAnnotation()) {
                    return clazz;
                }
            } catch (ClassNotFoundException e) {
                if (log.isDebugEnabled()) {
                    log.debug("Class not found for resolving from name '" + prefixedClassName + "'");
                }
            }
        } else {
            // Import is a package name
            String prefixedClassName = getPackageName(importName) + '.' + className;
            try {
                ClassLoader cl = Thread.currentThread().getContextClassLoader();
                Class clazz = Class.forName(prefixedClassName, true, cl);
                if (!requireAnnotation || clazz.isAnnotation()) {
                    return clazz;
                }
            } catch (ClassNotFoundException e) {
                if (log.isDebugEnabled()) {
                    log.debug("Class not found for resolving from name '" + prefixedClassName + "'");
                }
            }
        }
    }

    // try to resolve from method references
    for (String name : methodInvocationRef.keySet()) {
        if (JavaClassHelper.isSimpleNameFullyQualfied(className, name)) {
            try {
                ClassLoader cl = Thread.currentThread().getContextClassLoader();
                Class clazz = Class.forName(name, true, cl);
                if (!requireAnnotation || clazz.isAnnotation()) {
                    return clazz;
                }
            } catch (ClassNotFoundException e1) {
                if (log.isDebugEnabled()) {
                    log.debug("Class not found for resolving from method invocation ref:" + name);
                }
            }
        }
    }

    // No import worked, the class isn't resolved
    throw new ClassNotFoundException("Unknown class " + className);
}

From source file:fr.exanpe.tapestry.tldgen.taglib.builder.StructureBuilder.java

/**
 * Builds the output taglib structure/*w ww  . ja v  a2 s  .com*/
 * 
 * @param rootPackage the root package to look the components for
 * @param supportedPackages all sub packages to scan
 * @param urls the urls used to scan the packages
 * @return the structure containing the information on the taglib to generate
 * @throws MojoExecutionException if any unexpected error occurs
 */
public Taglib build(String rootPackage, String[] supportedPackages, URL[] urls) throws MojoExecutionException {
    Taglib taglib = new Taglib();

    log.debug("Creating taglib object model...");

    for (String subPackage : supportedPackages) {
        String pkgname = rootPackage + "." + subPackage;

        log.debug("Processing taglib for full package named : " + pkgname);

        Reflections reflections = new Reflections(new ConfigurationBuilder()
                .filterInputsBy(new FilterBuilder.Include(FilterBuilder.prefix(pkgname))).setUrls(urls)
                .setScanners(new TypesScanner()));

        Store store = reflections.getStore();

        // Return classes anaylised by TypeScanner
        Multimap<String, String> classes = store.getStoreMap().values().iterator().next();

        log.debug(String.format("%s classes to analyse for %s package...", classes.keySet().size(), pkgname));

        // Loop on found classes
        for (final String s : classes.keySet()) {
            Class<?> c;
            try {
                log.debug(String.format("Load class %s into classloader", s));
                c = Thread.currentThread().getContextClassLoader().loadClass(s);
            } catch (ClassNotFoundException e) {
                // should not happen as it has just been parsed by Reflection...
                log.error(e);
                throw new MojoExecutionException("Class loader internal error for class :" + s, e);
            }

            if (!c.isAnnotation() && !c.isAnonymousClass() && !c.isEnum() && !c.isInterface()
                    && !c.isLocalClass() && !c.isMemberClass() && !c.isSynthetic()
                    && !Modifier.isAbstract(c.getModifiers())) {
                log.debug("Processing Tag : " + c.getName());

                Tag tag = buildTagFromClass(rootPackage, c);
                taglib.getTags().add(tag);
            }
        }
    }

    log.debug("Taglib object model completed");
    return taglib;
}

From source file:com.sunchenbin.store.feilong.core.lang.ClassUtil.java

/**
 *  class info map for LOGGER.//ww  w .j  a v  a2  s .co m
 *
 * @param klass
 *            the clz
 * @return the map for log
 */
public static Map<String, Object> getClassInfoMapForLog(Class<?> klass) {
    if (Validator.isNullOrEmpty(klass)) {
        return Collections.emptyMap();
    }

    Map<String, Object> map = new LinkedHashMap<String, Object>();

    map.put("clz.getCanonicalName()", klass.getCanonicalName());//"com.sunchenbin.store.feilong.core.date.DatePattern"
    map.put("clz.getName()", klass.getName());//"com.sunchenbin.store.feilong.core.date.DatePattern"
    map.put("clz.getSimpleName()", klass.getSimpleName());//"DatePattern"

    map.put("clz.getComponentType()", klass.getComponentType());
    // ?? ,voidboolean?byte?char?short?int?long?float  double?
    map.put("clz.isPrimitive()", klass.isPrimitive());

    // ??,
    map.put("clz.isLocalClass()", klass.isLocalClass());
    // ????,?,?????
    map.put("clz.isMemberClass()", klass.isMemberClass());

    //isSynthetic()?Class????java??false,?true,JVM???,java??????
    map.put("clz.isSynthetic()", klass.isSynthetic());
    map.put("clz.isArray()", klass.isArray());
    map.put("clz.isAnnotation()", klass.isAnnotation());

    //??true
    map.put("clz.isAnonymousClass()", klass.isAnonymousClass());
    map.put("clz.isEnum()", klass.isEnum());

    return map;
}

From source file:org.ops4j.pax.web.service.jetty.internal.JettyServerWrapper.java

@SuppressWarnings("unchecked")
private HttpServiceContext addContext(final ContextModel model) {
    Bundle bundle = model.getBundle();//from w w w.j  a v a  2 s  . c o m
    BundleContext bundleContext = BundleUtils.getBundleContext(bundle);
    // scan for ServletContainerInitializers
    Set<Bundle> bundlesInClassSpace = ClassPathUtil.getBundlesInClassSpace(bundle, new HashSet<Bundle>());

    if (jettyBundle != null) {
        ClassPathUtil.getBundlesInClassSpace(jettyBundle, bundlesInClassSpace);
    }

    for (URL u : ClassPathUtil.findResources(bundlesInClassSpace, "/META-INF/services",
            "javax.servlet.ServletContainerInitializer", true)) {
        try {
            InputStream is = u.openStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            // only the first line is read, it contains the name of the
            // class.
            String className = reader.readLine();
            LOG.info("will add {} to ServletContainerInitializers", className);

            if (className.endsWith("JasperInitializer")) {
                LOG.info("Skipt {}, because specialized handler will be present", className);
                continue;
            }

            Class<?> initializerClass;

            try {
                initializerClass = bundle.loadClass(className);
            } catch (ClassNotFoundException ignore) {
                initializerClass = jettyBundle.loadClass(className);
            }

            // add those to the model contained ones
            Map<ServletContainerInitializer, Set<Class<?>>> containerInitializers = model
                    .getContainerInitializers();

            ServletContainerInitializer initializer = (ServletContainerInitializer) initializerClass
                    .newInstance();

            if (containerInitializers == null) {
                containerInitializers = new HashMap<ServletContainerInitializer, Set<Class<?>>>();
                model.setContainerInitializers(containerInitializers);
            }

            Set<Class<?>> setOfClasses = new HashSet<Class<?>>();
            // scan for @HandlesTypes
            HandlesTypes handlesTypes = initializerClass.getAnnotation(HandlesTypes.class);
            if (handlesTypes != null) {
                Class<?>[] classes = handlesTypes.value();

                for (Class<?> klass : classes) {
                    boolean isAnnotation = klass.isAnnotation();
                    boolean isInteraface = klass.isInterface();

                    if (isAnnotation) {
                        try {
                            BundleAnnotationFinder baf = new BundleAnnotationFinder(
                                    packageAdminTracker.getService(), bundle);
                            List<Class<?>> annotatedClasses = baf
                                    .findAnnotatedClasses((Class<? extends Annotation>) klass);
                            setOfClasses.addAll(annotatedClasses);
                        } catch (Exception e) {
                            LOG.warn("Failed to find annotated classes for ServletContainerInitializer", e);
                        }
                    } else if (isInteraface) {
                        BundleAssignableClassFinder basf = new BundleAssignableClassFinder(
                                packageAdminTracker.getService(), new Class[] { klass }, bundle);
                        Set<String> interfaces = basf.find();
                        for (String interfaceName : interfaces) {
                            setOfClasses.add(bundle.loadClass(interfaceName));
                        }
                    } else {
                        // class
                        BundleAssignableClassFinder basf = new BundleAssignableClassFinder(
                                packageAdminTracker.getService(), new Class[] { klass }, bundle);
                        Set<String> classNames = basf.find();
                        for (String klassName : classNames) {
                            setOfClasses.add(bundle.loadClass(klassName));
                        }
                    }
                }
            }
            containerInitializers.put(initializer, setOfClasses);
            LOG.info("added ServletContainerInitializer: {}", className);
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | IOException e) {
            LOG.warn(
                    "failed to parse and instantiate of javax.servlet.ServletContainerInitializer in classpath");
        }
    }

    HttpServiceContext context = new HttpServiceContext((HandlerContainer) getHandler(),
            model.getContextParams(), getContextAttributes(bundleContext), model.getContextName(),
            model.getHttpContext(), model.getAccessControllerContext(), model.getContainerInitializers(),
            model.getJettyWebXmlURL(), model.getVirtualHosts());
    context.setClassLoader(model.getClassLoader());
    Integer modelSessionTimeout = model.getSessionTimeout();
    if (modelSessionTimeout == null) {
        modelSessionTimeout = sessionTimeout;
    }
    String modelSessionCookie = model.getSessionCookie();
    if (modelSessionCookie == null) {
        modelSessionCookie = sessionCookie;
    }
    String modelSessionDomain = model.getSessionDomain();
    if (modelSessionDomain == null) {
        modelSessionDomain = sessionDomain;
    }
    String modelSessionPath = model.getSessionPath();
    if (modelSessionPath == null) {
        modelSessionPath = sessionPath;
    }
    String modelSessionUrl = model.getSessionUrl();
    if (modelSessionUrl == null) {
        modelSessionUrl = sessionUrl;
    }
    Boolean modelSessionCookieHttpOnly = model.getSessionCookieHttpOnly();
    if (modelSessionCookieHttpOnly == null) {
        modelSessionCookieHttpOnly = sessionCookieHttpOnly;
    }
    Boolean modelSessionSecure = model.getSessionCookieSecure();
    if (modelSessionSecure == null) {
        modelSessionSecure = sessionCookieSecure;
    }
    String workerName = model.getSessionWorkerName();
    if (workerName == null) {
        workerName = sessionWorkerName;
    }
    configureSessionManager(context, modelSessionTimeout, modelSessionCookie, modelSessionDomain,
            modelSessionPath, modelSessionUrl, modelSessionCookieHttpOnly, modelSessionSecure, workerName,
            lazyLoad, storeDirectory);

    if (model.getRealmName() != null && model.getAuthMethod() != null) {
        configureSecurity(context, model.getRealmName(), model.getAuthMethod(), model.getFormLoginPage(),
                model.getFormErrorPage());
    }

    configureJspConfigDescriptor(context, model);

    LOG.debug("Added servlet context: " + context);

    if (isStarted()) {
        try {
            LOG.debug("(Re)starting servlet contexts...");
            // start the server handler if not already started
            Handler serverHandler = getHandler();
            if (!serverHandler.isStarted() && !serverHandler.isStarting()) {
                serverHandler.start();
            }
            // if the server handler is a handler collection, seems like
            // jetty will not automatically
            // start inner handlers. So, force the start of the created
            // context
            if (!context.isStarted() && !context.isStarting()) {
                LOG.debug("Registering ServletContext as service. ");
                Dictionary<String, String> properties = new Hashtable<String, String>();
                properties.put("osgi.web.symbolicname", bundle.getSymbolicName());

                Dictionary<?, ?> headers = bundle.getHeaders();
                String version = (String) headers.get(Constants.BUNDLE_VERSION);
                if (version != null && version.length() > 0) {
                    properties.put("osgi.web.version", version);
                }

                // Context servletContext = context.getServletContext();
                String webContextPath = context.getContextPath();

                properties.put("osgi.web.contextpath", webContextPath);

                context.registerService(bundleContext, properties);
                LOG.debug("ServletContext registered as service. ");

            }
            // CHECKSTYLE:OFF
        } catch (Exception ignore) {
            LOG.error("Could not start the servlet context for http context [" + model.getHttpContext() + "]",
                    ignore);
            if (ignore instanceof MultiException) {
                LOG.error("MultiException found: ");
                MultiException mex = (MultiException) ignore;
                List<Throwable> throwables = mex.getThrowables();
                for (Throwable throwable : throwables) {
                    LOG.error(throwable.getMessage());
                }
            }
        }
        // CHECKSTYLE:ON
    }
    return context;
}

From source file:com.feilong.commons.core.lang.ClassUtil.java

/**
 *  class info map for log.//from w  w  w  .  j  a v a2s .c  o  m
 *
 * @param klass
 *            the clz
 * @return the map for log
 */
public static Map<String, Object> getClassInfoMapForLog(Class<?> klass) {

    Map<String, Object> map = new LinkedHashMap<String, Object>();

    //"clz.getCanonicalName()": "com.feilong.commons.core.date.DatePattern",
    //"clz.getName()": "com.feilong.commons.core.date.DatePattern",
    //"clz.getSimpleName()": "DatePattern",

    // getCanonicalName ( Java Language Specification ??) && getName
    //??class?array?
    // getName[[Ljava.lang.String?getCanonicalName?
    map.put("clz.getCanonicalName()", klass.getCanonicalName());
    map.put("clz.getName()", klass.getName());
    map.put("clz.getSimpleName()", klass.getSimpleName());

    map.put("clz.getComponentType()", klass.getComponentType());
    // ?? voidboolean?byte?char?short?int?long?float  double?
    map.put("clz.isPrimitive()", klass.isPrimitive());

    // ??,
    map.put("clz.isLocalClass()", klass.isLocalClass());
    // ????,??????
    map.put("clz.isMemberClass()", klass.isMemberClass());

    //isSynthetic()?Class????java??false?trueJVM???java??????
    map.put("clz.isSynthetic()", klass.isSynthetic());
    map.put("clz.isArray()", klass.isArray());
    map.put("clz.isAnnotation()", klass.isAnnotation());

    //??true
    map.put("clz.isAnonymousClass()", klass.isAnonymousClass());
    map.put("clz.isEnum()", klass.isEnum());

    return map;
    //      Class<?> klass = this.getClass();
    //
    //      TypeVariable<?>[] typeParameters = klass.getTypeParameters();
    //      TypeVariable<?> typeVariable = typeParameters[0];
    //
    //      Type[] bounds = typeVariable.getBounds();
    //
    //      Type bound = bounds[0];
    //
    //      if (log.isDebugEnabled()){
    //         log.debug("" + (bound instanceof ParameterizedType));
    //      }
    //
    //      Class<T> modelClass = ReflectUtil.getGenericModelClass(klass);
    //      return modelClass;
}

From source file:org.brekka.stillingar.spring.config.ConfigurationServiceBeanDefinitionParser.java

protected void preparePostProcessor(Element element, ParserContext parserContext) {
    String id = element.getAttribute("id");
    String name = getName(element);
    BeanDefinitionBuilder postProcessor = BeanDefinitionBuilder
            .genericBeanDefinition(ConfigurationBeanPostProcessor.class);
    postProcessor.addConstructorArgValue(name);
    postProcessor.addConstructorArgReference(id);
    Element annotationConfigElement = selectSingleChildElement(element, "annotation-config", true);
    if (annotationConfigElement != null) {
        String marker = annotationConfigElement.getAttribute("marker");
        if (StringUtils.hasLength(marker)) {
            Class<?> theClass = ClassUtils.resolveClassName(marker,
                    Thread.currentThread().getContextClassLoader());
            if (!theClass.isAnnotation()) {
                throw new ConfigurationException(String.format("The class '%s' is not an annotation", marker));
            }//from w w  w  .  jav a  2  s. co  m
            postProcessor.addPropertyValue("markerAnnotation", theClass);
        }
    }
    parserContext.registerBeanComponent(
            new BeanComponentDefinition(postProcessor.getBeanDefinition(), id + "-postProcessor"));
}

From source file:com.github.wshackle.java4cpp.J4CppMain.java

public static boolean isAddableClass(Class<?> clss, Set<Class> excludedClasses) {
    if (clss.isArray() || clss.isSynthetic() || clss.isAnnotation() || clss.isPrimitive()) {
        return false;
    }//from  ww  w. ja  v  a2s .c o m
    //        if(clss.getCanonicalName().contains("Dialog") || clss.getName().contains("ModalExlusionType")) {
    //            if(verbose) System.out.println("clss = " + clss);
    //        }
    //        if (clss.getEnclosingClass() != null) {
    //            return false;
    //        }
    String canonicalName = null;
    try {
        canonicalName = clss.getCanonicalName();
    } catch (Throwable t) {
        // leaving canonicalName null is enough
    }
    if (null == canonicalName) {
        return false;
    }
    if (canonicalName.indexOf('$') >= 0) {
        return false;
    }
    String pkgNames[] = clss.getCanonicalName().split("\\.");
    for (int i = 0; i < pkgNames.length; i++) {
        String pkgName = pkgNames[i];
        if (badNames.contains(pkgName)) {
            return false;
        }
    }
    Method ma[] = null;
    try {
        ma = clss.getDeclaredMethods();
    } catch (Throwable t) {
        // leaving canonicalName null is enough
    }
    if (null == ma) {
        return false;
    }
    return !excludedClasses.contains(clss);
}

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

@SuppressWarnings("unchecked")
protected static <T> void __doFindClassByZip(Collection<Class<T>> collections, Class<T> clazz,
        String packageName, URL zipUrl, Class<?> callingClass) {
    ZipInputStream _zipStream = null;
    try {/*from www .j a  va2 s.  c o  m*/
        String _zipFilePath = zipUrl.toString();
        if (_zipFilePath.indexOf('!') > 0) {
            _zipFilePath = StringUtils.substringBetween(zipUrl.toString(), "zip:", "!");
        } else {
            _zipFilePath = StringUtils.substringAfter(zipUrl.toString(), "zip:");
        }
        _zipStream = new ZipInputStream(new FileInputStream(new File(_zipFilePath)));
        ZipEntry _zipEntry = null;
        while (null != (_zipEntry = _zipStream.getNextEntry())) {
            if (!_zipEntry.isDirectory()) {
                if (_zipEntry.getName().endsWith(".class") && _zipEntry.getName().indexOf('$') < 0) {
                    Class<?> _class = __doProcessEntry(zipUrl, _zipEntry);
                    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);
                        }
                    }
                }
            }
            _zipStream.closeEntry();
        }
    } catch (Exception e) {
        _LOG.warn("", RuntimeUtils.unwrapThrow(e));
    } finally {
        if (_zipStream != null) {
            try {
                _zipStream.close();
            } catch (IOException e) {
                _LOG.warn("", RuntimeUtils.unwrapThrow(e));
            }
        }
    }
}