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:org.apache.sling.testing.mock.osgi.OsgiServiceUtil.java

private static Method getMethodWithAnyCombinationArgs(Class clazz, String methodName, Class<?>[] types) {
    Method[] methods = clazz.getDeclaredMethods();
    for (Method method : methods) {
        if (StringUtils.equals(method.getName(), methodName) && method.getParameterTypes().length > 1) {
            boolean foundMismatch = false;
            for (Class<?> parameterType : method.getParameterTypes()) {
                boolean foundAnyMatch = false;
                for (int i = 0; i < types.length; i++) {
                    if ((parameterType == types[i])
                            || (types[i] == Annotation.class && parameterType.isAnnotation())) {
                        foundAnyMatch = true;
                        break;
                    }//www  . j  a va2  s .c  om
                }
                if (!foundAnyMatch) {
                    foundMismatch = true;
                    break;
                }
            }
            if (!foundMismatch) {
                return method;
            }
        }
    }
    // not found? check super classes
    Class<?> superClass = clazz.getSuperclass();
    if (superClass != null && superClass != Object.class) {
        return getMethodWithAnyCombinationArgs(superClass, methodName, types);
    }
    return null;
}

From source file:org.broadinstitute.gatk.utils.help.GenericDocumentationHandler.java

/**
 * Attempt to instantiate class c, if possible.  Returns null if this proves impossible.
 *
 * @param c// w ww.  j  av a2s.  c om
 * @return
 */
private Object makeInstanceIfPossible(Class c) {
    Object instance = null;
    try {
        // don't try to make something where we will obviously fail
        if (!c.isEnum() && !c.isAnnotation() && !c.isAnonymousClass() && !c.isArray()
                && !c.isPrimitive() & JVMUtils.isConcrete(c)) {
            instance = c.newInstance();
            //System.out.printf("Created object of class %s => %s%n", c, instance);
            return instance;
        } else
            return null;
    } catch (IllegalAccessException e) {
    } catch (InstantiationException e) {
    } catch (ExceptionInInitializerError e) {
    } catch (SecurityException e) {
    }
    // this last one is super dangerous, but some of these methods catch ClassNotFoundExceptions
    // and rethrow then as RuntimeExceptions
    catch (RuntimeException e) {
    }

    return instance;
}

From source file:org.jadira.scanner.classpath.types.JParameter.java

@Override
public JType getType() throws ClasspathAccessException {

    Class<?> clazz;
    if (enclosingOperation instanceof JConstructor || enclosingOperation instanceof JMethod) {
        MethodInfo methodInfo = ((JOperation) enclosingOperation).getMethodInfo();
        String[] paramTypeNames = JavassistMethodInfoHelper.getMethodParamTypeNames(methodInfo);
        clazz = decodeFieldType(paramTypeNames[getIndex()]);

    } else {/*  w  w w .j  a v a  2  s.c  o  m*/
        throw new ClasspathAccessException("Invalid parameter index: " + index);
    }

    if (clazz.isAnnotation()) {
        try {
            return new JAnnotation<java.lang.annotation.Annotation>(
                    (java.lang.annotation.Annotation) clazz.newInstance(), this, getResolver());
        } catch (InstantiationException e) {
            throw new ClasspathAccessException("Problem instantiating annotation: " + e.getMessage(), e);
        } catch (IllegalAccessException e) {
            throw new ClasspathAccessException("Problem accessing annotation: " + e.getMessage(), e);
        }
    } else if (clazz.isInterface()) {
        return new JInterface(clazz.getName(), getResolver());
    } else {
        JClass jClass = new JClass(clazz.getName(), getResolver());
        return jClass;
    }
}

From source file:org.jboss.dashboard.commons.misc.ReflectionUtils.java

public static List<Field> getClassFields(Class clazz, Class type, boolean isStatic, String[] fieldsToIgnore) {
    List<Field> results = new ArrayList<Field>();
    if (clazz == null)
        return results;
    if (clazz.isPrimitive())
        return results;
    if (clazz.isAnnotation())
        return results;
    if (clazz.isInterface())
        return results;
    if (clazz.isEnum())
        return results;

    Collection<String> toIgnore = fieldsToIgnore != null ? Arrays.asList(fieldsToIgnore)
            : Collections.EMPTY_SET;
    Field[] fields = clazz.getDeclaredFields();

    for (int i = 0; i < fields.length; i++) {
        Field field = fields[i];/*from w w w  . j ava 2  s . c  o m*/
        if (toIgnore.contains(field.getName()))
            continue;
        if (isStatic && !Modifier.isStatic(field.getModifiers()))
            continue;
        if (!isStatic && Modifier.isStatic(field.getModifiers()))
            continue;
        if (type != null && !field.getType().equals(type))
            continue;
        results.add(field);
    }
    return results;
}

From source file:org.jgentleframework.core.factory.support.CommonFactory.java

/**
 * Executes process after bean is created.
 * //from w  w w. j  a va2  s  .c  om
 * @param targetClass
 *            the target object class
 * @param metaObj
 *            the {@link MetaDefObject} instance
 * @param provider
 *            current provider
 * @param result
 *            the object bean has just bean instantiated.
 * @param definition
 *            the {@link Definition}
 * @throws IllegalArgumentException
 *             the illegal argument exception
 * @throws SecurityException
 *             the security exception
 * @throws InstantiationException
 *             the instantiation exception
 * @throws IllegalAccessException
 *             the illegal access exception
 * @throws InvocationTargetException
 *             the invocation target exception
 * @throws NoSuchMethodException
 *             the no such method exception
 */
public void executeProcessAfterBeanCreated(Class<?> targetClass, MetaDefObject metaObj, Provider provider,
        Object result, Definition definition) throws IllegalArgumentException, SecurityException,
        InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException {

    if (!targetClass.isAnnotation()) {
        /*
         * X l thng tin cc inject non-invocation
         */
        InOutExecutor.executesInjectingAndFiltering(metaObj.getInjectedFields(), metaObj.getSetters(), provider,
                result, definition);
        // embed
        embedProvider(provider, result);
        embedDefinition(definition, result);
        embedTargetClasses(new Class<?>[] { targetClass }, result);
        // thc thi init
        doInit(definition, result, targetClass);
        /*
         * X l thng tin cc outject non-invocation
         */
        InOutExecutor.executesFieldOutjecting(metaObj.getOutjectedFields(), provider, result, definition);
        InOutExecutor.executesMethodOutjecting(metaObj.getGetters(), provider, result, definition);
    }
}

From source file:org.jgentleframework.core.factory.support.CoreProcessorImpl.java

@SuppressWarnings("unchecked")
@Override//from ww w  . jav  a 2s.com
public Object handle(Selector targetSelector, Object previousResult)
        throws InvocationTargetException, IllegalArgumentException, SecurityException, InstantiationException,
        IllegalAccessException, NoSuchMethodException {

    if (!ReflectUtils.isCast(CoreInstantiationSelector.class, targetSelector)) {
        if (log.isFatalEnabled()) {
            log.fatal("Target selector can not be casted to '" + CoreInstantiationSelector.class.toString()
                    + "'");
        }
        throw new IllegalPropertyException(
                "Target selector can not be casted to '" + CoreInstantiationSelector.class.toString() + "'");
    }
    Object result = null;
    Definition definition = targetSelector.getDefinition();
    Class<?> targetClass = targetSelector.getTargetClass();
    CoreInstantiationSelector selector = (CoreInstantiationSelector) targetSelector;
    boolean runtimeLoading = definition != null && definition.isAnnotationPresent(AlwaysReload.class)
            ? definition.getAnnotation(AlwaysReload.class).value()
            : false;
    // create bean instance
    if (targetSelector instanceof InstantiationSelectorImpl) {
        InstantiationSelector instSelector = (InstantiationSelector) targetSelector;
        // nu bean  c khi to 1 phn trc 
        if (previousResult != null && (targetClass.isAnnotation() || targetClass.isInterface())) {
            throw new InterceptionException(
                    "Bean instantiation is not supported or completed if target class is "
                            + "annotation or interface and if at least one 'instantiation' interceptor "
                            + "has instantiated the corresponding 'object bean'");
        } else {
            Map<Method, MethodAspectPair> methodAspectList = new HashMap<Method, MethodAspectPair>();
            Map<Interceptor, Matcher<Definition>> map = instSelector.getMapMatcherInterceptor();
            final List<Method> methodList = new ArrayList<Method>();
            final Field[] fieldList = ReflectUtils.getDeclaredFields(targetClass, false, true);
            Enhancer.getMethods(targetClass, null, methodList);
            boolean invocationINOUT = false;
            ElementAspectFactory elementAspectFactory = new ElementAspectFactory();
            /*
             * perform method interceptor
             */
            MethodInterceptor[] methodIcptLst = instSelector.getMethodInterceptors();
            for (Method method : methodList) {
                invocationINOUT = invocationINOUT == false ? InterceptorUtils.isInvocation(definition, method)
                        : invocationINOUT;
                // creates Aspect Pair
                MethodAspectPair aspectPair = elementAspectFactory.analysesMethod(methodIcptLst, map,
                        definition, method);
                // performs advice
                executesAdvice(definition, method, provider, runtimeLoading, aspectPair);
                if (aspectPair.hasInterceptors())
                    methodAspectList.put(method, aspectPair);
            }
            /*
             * perform field interceptor
             */
            FieldInterceptor[] fieldIcpLst = instSelector.getFieldInterceptors();
            if (!targetClass.isAnnotation()) {
                for (Field field : fieldList) {
                    invocationINOUT = invocationINOUT == false
                            ? InterceptorUtils.isInvocation(definition, field)
                            : invocationINOUT;
                    // creates Aspect Pair
                    FieldAspectPair fieldAspectPair = elementAspectFactory.analysesField(fieldIcpLst, map,
                            definition, field);
                    if (fieldAspectPair.hasInterceptors()) {
                        Method setter = Utils.getDefaultSetter(targetClass, field.getName());
                        Method getter = Utils.getDefaultGetter(targetClass, field.getName());
                        if (getter == null || setter == null) {
                            throw new InterceptionException(
                                    "Does not found setter or getter of field '" + field.getName() + "'");
                        }
                        MethodInterceptor interceptor = InterceptorUtils
                                .createsFieldStackMethodInterceptor(field);
                        if (methodAspectList.containsKey(setter))
                            methodAspectList.get(setter).add(interceptor);
                        else
                            methodAspectList.put(setter, new MethodAspectPair(setter, interceptor));
                        if (methodAspectList.containsKey(getter))
                            methodAspectList.get(getter).add(interceptor);
                        else
                            methodAspectList.put(getter, new MethodAspectPair(getter, interceptor));
                    }
                }
            }
            /*
             * perform invocation in/out or annotation attributes injection
             */
            executesInOut(targetClass, definition, provider, runtimeLoading, methodAspectList, invocationINOUT);
            // Creates callbacks.
            Callback[] callbacks = new Callback[methodList.size() + 1];
            Class<? extends Callback>[] callbackTypes = new Class[methodList.size() + 1];
            for (int i = 0; i < methodList.size(); i++) {
                MethodAspectPair pair = methodAspectList.get(methodList.get(i));
                if (pair == null) {
                    callbacks[i] = NoOp.INSTANCE;
                    callbackTypes[i] = NoOp.class;
                } else {
                    callbacks[i] = new MethodInterceptorStackCallback(pair.getMethod(), previousResult,
                            pair.interceptors.toArray(new MethodInterceptor[pair.interceptors.size()]));
                    callbackTypes[i] = net.sf.cglib.proxy.MethodInterceptor.class;
                }
            }
            callbacks[methodList.size()] = new ReturnScopeNameMethodInterceptor(selector.getScopeName());
            callbackTypes[methodList.size()] = net.sf.cglib.proxy.MethodInterceptor.class;
            // Nu khng tm thy bt k ch nh khi to interceptor no
            // ==> t ng return null.
            if (methodAspectList.size() == 0 && (targetClass.isInterface())) {
                return NullClass.class;
            }
            // Create the proxied class.
            final Method returnScopeNameMethod = ReturnScopeName.class.getDeclaredMethod("returnsScopeName");
            Enhancer enhancer = new Enhancer();
            if (targetClass.isAnnotation() || targetClass.isInterface())
                enhancer.setInterfaces(new Class<?>[] { targetClass, ReturnScopeName.class });
            else {
                enhancer.setSuperclass(targetClass);
                enhancer.setInterfaces(new Class<?>[] { ReturnScopeName.class });
            }
            enhancer.setCallbackFilter(new CallbackFilter() {
                public int accept(Method method) {

                    if (method.equals(returnScopeNameMethod))
                        return methodList.size();
                    return methodList.indexOf(method);
                }
            });
            enhancer.setCallbackTypes(callbackTypes);
            enhancer.setUseFactory(false);
            enhancer.setUseCache(true);
            enhancer.setNamingPolicy(new JGentleNamingPolicy());
            Class<?> proxied = enhancer.createClass();
            Enhancer.registerStaticCallbacks(proxied, callbacks);
            MetaDefObject metaObj = new MetaDefObject();
            findInOutNonRuntime(metaObj, definition);
            CachedConstructor cons = Utils.createConstructionProxy(definition, proxied,
                    instSelector.getArgTypes(), metaObj);
            selector.getCachingList().put(definition, cons);
            result = cons.newInstance(instSelector.getArgs());
            // executes process after bean is created
            prepareSingletonBean(selector, provider, result);
            CommonFactory.singleton().executeProcessAfterBeanCreated(targetClass, metaObj, provider, result,
                    definition);
        }
    } else if (targetSelector instanceof CoreInstantiationSelectorImpl
            && !(targetSelector instanceof InstantiationSelectorImpl)) {
        result = createPureBeanInstance(targetSelector, targetClass, definition, provider, runtimeLoading);
    }
    return result;
}

From source file:org.jgentleframework.core.factory.support.CoreProcessorImpl.java

@SuppressWarnings("unchecked")
@Override//from   w ww  .jav a2 s. c om
protected CachedConstructor createConstructionProxy(final CoreInstantiationSelector selector,
        Class<?> interfaze, net.sf.cglib.proxy.MethodInterceptor interceptor, final List<Method> methodList,
        MetaDefObject mdo) throws SecurityException, NoSuchMethodException {

    Assertor.notNull(interceptor, "The given interceptor must not be null !");
    Assertor.notNull(interceptor, "The given method list must not be null !");
    // Create
    Enhancer enhancer = new Enhancer();
    enhancer.setSuperclass(selector.getTargetClass());
    if (interfaze != null && interfaze.isAnnotation())
        enhancer.setInterfaces(new Class<?>[] { interfaze, Annotation.class, ReturnScopeName.class });
    else if (interfaze != null && interfaze.isInterface())
        enhancer.setInterfaces(new Class<?>[] { interfaze, ReturnScopeName.class });
    else {
        enhancer.setInterfaces(new Class<?>[] { ReturnScopeName.class });
    }
    final Method returnScopeNameMethod = ReturnScopeName.class.getDeclaredMethod("returnsScopeName");
    Callback[] callbacks = new Callback[] { NoOp.INSTANCE, interceptor,
            new ReturnScopeNameMethodInterceptor(selector.getScopeName()) };
    Class<? extends Callback>[] callbackTypes = new Class[] { NoOp.class,
            net.sf.cglib.proxy.MethodInterceptor.class, net.sf.cglib.proxy.MethodInterceptor.class };
    enhancer.setCallbackFilter(new CallbackFilter() {
        @Override
        public int accept(Method method) {

            if (methodList != null && methodList.contains(method) && !selector.getTargetClass().isAnnotation())
                return 1;
            else if (selector.getTargetClass().isAnnotation())
                return 1;
            else if (method.equals(returnScopeNameMethod))
                return 2;
            else
                return 0;
        }
    });
    enhancer.setCallbackTypes(callbackTypes);
    enhancer.setUseFactory(false);
    enhancer.setUseCache(true);
    enhancer.setNamingPolicy(new JGentleNamingPolicy());
    Class<?> proxied = enhancer.createClass();
    // Store callbacks.
    Enhancer.registerStaticCallbacks(proxied, callbacks);
    CachedConstructor cons = Utils.createConstructionProxy(selector.getDefinition(), proxied,
            selector.getArgTypes(), mdo);
    return cons;
}

From source file:org.makersoft.mvc.builder.PackageBasedUrlPathBuilder.java

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

From source file:org.mule.util.scan.ClasspathScanner.java

/**
 * Works out the correct scanner based on the class passed in
 * <p/>//from www  .  j a  v  a  2 s. c o  m
 * Note that these could be better architected by breaking out filters into strategy objects, but for now this
 * suits my needs
 *
 * @param clazz the type to scan for
 * @return a scanner suitable for handling the type passed in
 * @see AnnotationsScanner
 * @see InterfaceClassScanner
 * @see ImplementationClassScanner
 */
protected ClassScanner getScanner(Class<?> clazz) {
    if (clazz.isInterface()) {
        if (clazz.isAnnotation()) {
            @SuppressWarnings("unchecked")
            Class<? extends Annotation> annotationClass = (Class<? extends Annotation>) clazz;

            AnnotationFilter filter = null;
            Annotation[] annos = clazz.getDeclaredAnnotations();
            for (int i = 0; i < annos.length; i++) {
                Annotation anno = annos[i];
                if (anno instanceof Target) {
                    if (((Target) anno).value()[0] == ElementType.ANNOTATION_TYPE) {
                        filter = new MetaAnnotationTypeFilter(annotationClass, classLoader);
                    }
                }
            }
            if (filter == null) {
                filter = new AnnotationTypeFilter(annotationClass);
            }
            return new AnnotationsScanner(filter);
        } else {
            return new InterfaceClassScanner(clazz);
        }
    } else {
        return new ImplementationClassScanner(clazz);
    }
}

From source file:org.rapidoid.util.RapidoidThingsTest.java

@Test
public void classesShouldExtendRapidoidThing() {
    for (String cls : Cls.getRapidoidClasses()) {
        Class<?> clazz = Cls.get(cls);

        if (!clazz.isInterface() && !clazz.isEnum() && !clazz.isAnnotation()) {
            U.must(RapidoidThing.class.isAssignableFrom(clazz) || clazz == TestCommons.class
                    || cls.startsWith("org.rapidoid.fluent.") || cls.startsWith("org.rapidoid.benchmark.")
                    || Exception.class.isAssignableFrom(clazz) || ClassLoader.class.isAssignableFrom(clazz)
                    || HibernatePersistenceProvider.class.isAssignableFrom(clazz)
                    || OutputStream.class.isAssignableFrom(clazz) || Map.class.isAssignableFrom(clazz)
                    || AbstractMojo.class.isAssignableFrom(clazz)
                    || EmbeddedMavenCli.class.isAssignableFrom(clazz)
                    || JsonSerializer.class.isAssignableFrom(clazz)
                    || JsonDeserializer.class.isAssignableFrom(clazz)
                    || LogFactory.class.isAssignableFrom(clazz) || Thread.class.isAssignableFrom(clazz),
                    "" + cls);
        }//from   ww w.j a v  a 2 s  .  c  o m
    }
}