protected void _addClassMixIns(AnnotationMap annotations, Class<?> toMask, Class<?> mixin) { if (mixin == null) { return; } // Ok, first: annotations from mix-in class itself: for (Annotation a : mixin.getDeclaredAnnotations()) { if (_annotationIntrospector.isHandled(a)) { annotations.addIfNotPresent(a); } } /* And then from its supertypes, if any. But note that we will * only consider super-types up until reaching the masked * class (if found); this because often mix-in class * is a sub-class (for convenience reasons). And if so, we * absolutely must NOT include super types of masked class, * as that would inverse precedence of annotations. */ for (Class<?> parent : ClassUtil.findSuperTypes(mixin, toMask)) { for (Annotation a : parent.getDeclaredAnnotations()) { if (_annotationIntrospector.isHandled(a)) { annotations.addIfNotPresent(a); } } } }
/** * Initialization method that will recursively collect Jackson annotations for this class and all * super classes and interfaces. * * <p>Starting with 1.2, it will also apply mix-in annotations, as per [JACKSON-76] */ protected void resolveClassAnnotations() { _classAnnotations = new AnnotationMap(); // add mix-in annotations first (overrides) if (_primaryMixIn != null) { _addClassMixIns(_classAnnotations, _class, _primaryMixIn); } // first, annotations from the class itself: for (Annotation a : _class.getDeclaredAnnotations()) { if (_annotationIntrospector.isHandled(a)) { _classAnnotations.addIfNotPresent(a); } } // and then from super types for (Class<?> cls : _superTypes) { // and mix mix-in annotations in-between _addClassMixIns(_classAnnotations, cls); for (Annotation a : cls.getDeclaredAnnotations()) { if (_annotationIntrospector.isHandled(a)) { _classAnnotations.addIfNotPresent(a); } } } /* and finally... any annotations there might be for plain * old Object.class: separate because for all other purposes * it is just ignored (not included in super types) */ /* 12-Jul-2009, tatu: Should this be done for interfaces too? * For now, yes, seems useful for some cases, and not harmful * for any? */ _addClassMixIns(_classAnnotations, Object.class); }
private void assertAnnotations(Class<?> type) { assertThat( describe(type).getDeclaredAnnotations(), hasItems( new AnnotationList.ForLoadedAnnotation(type.getDeclaredAnnotations()) .toArray(new AnnotationDescription[type.getDeclaredAnnotations().length]))); assertThat( describe(type).getDeclaredAnnotations().size(), is(type.getDeclaredAnnotations().length)); assertThat( describe(type).getInheritedAnnotations(), hasItems( new AnnotationList.ForLoadedAnnotation(type.getAnnotations()) .toArray(new AnnotationDescription[type.getAnnotations().length]))); assertThat(describe(type).getInheritedAnnotations().size(), is(type.getAnnotations().length)); }
private void verifyExternalClass(final Class clazz) { // don't recommended to instantiate the class doing clazz.newInstance(). clazz.getDeclaredConstructors(); clazz.getDeclaredFields(); clazz.getDeclaredMethods(); clazz.getDeclaredClasses(); clazz.getDeclaredAnnotations(); }
private GenerateForm getFormAnnotation(Class formClass) { GenerateForm formAnnotation = null; for (Annotation annotation : formClass.getDeclaredAnnotations()) { Log.i(TAG, "class annotation: " + annotation); if (annotation instanceof GenerateForm) { formAnnotation = (GenerateForm) annotation; break; } } return formAnnotation; }
private String getName() { Class<T> type = getType(); for (Annotation annotation : type.getDeclaredAnnotations()) { if (annotation.annotationType().isAssignableFrom(PreferenceFile.class)) { PreferenceFile preferenceFileAnnotation = (PreferenceFile) annotation; return preferenceFileAnnotation.name(); } } return type.getSimpleName(); }
private void collectAnnotations( Class<?> source, MultiValueMap<Class<?>, Annotation> annotations, HashSet<Class<?>> seen) { if (source != null && seen.add(source)) { for (Annotation annotation : source.getDeclaredAnnotations()) { if (!AnnotationUtils.isInJavaLangAnnotationPackage(annotation)) { if (ANNOTATION_NAMES.contains(annotation.annotationType().getName())) { annotations.add(source, annotation); } collectAnnotations(annotation.annotationType(), annotations, seen); } } collectAnnotations(source.getSuperclass(), annotations, seen); } }
public void init(Class... clss) { List<Class> list = new LinkedList<Class>(); for (Class cls : clss) { if (cls.isAnnotationPresent(Implement.class)) { list.add(cls); for (Annotation ann : cls.getDeclaredAnnotations()) { if (ann instanceof Implement) { try { m_objects.put(cls, ((Implement) ann).value().newInstance()); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } } } } }
protected Map<String, Set<JSONWebServiceActionMapping>> getServiceJSONWebServiceActionMappingsMap( String contextName) { Map<String, Set<JSONWebServiceActionMapping>> jsonWebServiceActionMappingsMap = new LinkedHashMap<>(); List<JSONWebServiceActionMapping> jsonWebServiceActionMappings = _jsonWebServiceActionsManager.getJSONWebServiceActionMappings(contextName); for (JSONWebServiceActionMapping jsonWebServiceActionMapping : jsonWebServiceActionMappings) { Object actionObject = jsonWebServiceActionMapping.getActionObject(); Class<?> serviceClass = actionObject.getClass(); Class[] serviceInterfaces = serviceClass.getInterfaces(); for (Class<?> serviceInterface : serviceInterfaces) { Annotation[] declaredAnnotations = serviceInterface.getDeclaredAnnotations(); for (Annotation declaredAnnotation : declaredAnnotations) { if (!(declaredAnnotation instanceof AccessControlled)) { continue; } String serviceClassName = serviceInterface.getName(); Set<JSONWebServiceActionMapping> jsonWebServiceActionMappingsSet = jsonWebServiceActionMappingsMap.get(serviceClassName); if (jsonWebServiceActionMappingsSet == null) { jsonWebServiceActionMappingsSet = new LinkedHashSet<>(); jsonWebServiceActionMappingsMap.put(serviceClassName, jsonWebServiceActionMappingsSet); } jsonWebServiceActionMappingsSet.add(jsonWebServiceActionMapping); } } } return jsonWebServiceActionMappingsMap; }
/** * Finds the interfaces that implement component roles by looking recursively in all interfaces of * the passed component implementation class. If the roles annotation value is specified then use * the specified list instead of doing auto-discovery. Also note that we support component classes * implementing JSR 330's {@link javax.inject.Provider} (and thus without a component role * annotation). * * @param componentClass the component implementation class for which to find the component roles * it implements * @return the list of component role classes implemented * @deprecated since 4.0M1 use {@link #findComponentRoleTypes(Class)} instead */ @Deprecated public Set<Class<?>> findComponentRoleClasses(Class<?> componentClass) { // Note: We use a Set to ensure that we don't register duplicate roles. Set<Class<?>> classes = new LinkedHashSet<Class<?>>(); Component component = componentClass.getAnnotation(Component.class); if (component != null && component.roles().length > 0) { classes.addAll(Arrays.asList(component.roles())); } else { // Look in both superclass and interfaces for @ComponentRole or javax.inject.Provider for (Class<?> interfaceClass : componentClass.getInterfaces()) { // Handle superclass of interfaces classes.addAll(findComponentRoleClasses(interfaceClass)); // Handle interfaces directly declared in the passed component class for (Annotation annotation : interfaceClass.getDeclaredAnnotations()) { if (annotation.annotationType() == ComponentRole.class) { classes.add(interfaceClass); } } // Handle javax.inject.Provider if (Provider.class.isAssignableFrom(interfaceClass)) { classes.add(interfaceClass); } } // Note that we need to look into the superclass since the super class can itself implements // an interface // that has the @ComponentRole annotation. Class<?> superClass = componentClass.getSuperclass(); if (superClass != null && superClass != Object.class) { classes.addAll(findComponentRoleClasses(superClass)); } } return classes; }
/** * This method is used to filter classes that are added to the {@link DeployedUnit}. When this * method is used, only classes that are meant to be used with serialization are added to the * deployment. This feature can be used to, for example, make sure that * non-serialization-compatible classes (such as interfaces), do not complicate the use of a * deployment with the remote services (REST/JMS/WS). Note to other developers, it's possible that * classpath problems may arise, because of either classloader or lazy class resolution problems: * I simply don't know enough about the inner workings of the JAXB implementations (plural!) to * figure this out. * * @param deployedUnit The {@link DeployedUnit} to which the classes are added. The {@link * DeployedUnit} to which the classes are added. The {@link DeployedUnit} to which the classes * are added. * @param classToAdd The class to add to the {@link DeployedUnit}. */ private static void filterClassesAddedToDeployedUnit( DeployedUnit deployedUnit, Class classToAdd) { if (classToAdd.isInterface() || classToAdd.isAnnotation() || classToAdd.isLocalClass() || classToAdd.isMemberClass()) { return; } boolean jaxbClass = false; boolean remoteableClass = false; // @XmlRootElement and @XmlType may be used with inheritance for (Annotation anno : classToAdd.getAnnotations()) { if (XmlRootElement.class.equals(anno.annotationType())) { jaxbClass = true; break; } if (XmlType.class.equals(anno.annotationType())) { jaxbClass = true; break; } } // @Remotable is not inheritable, and may not be used as such for (Annotation anno : classToAdd.getDeclaredAnnotations()) { if (Remotable.class.equals(anno.annotationType())) { remoteableClass = true; break; } } if (jaxbClass || remoteableClass) { DeployedUnitImpl deployedUnitImpl = (DeployedUnitImpl) deployedUnit; deployedUnitImpl.addClass(classToAdd); } }
/** * Works out the correct scanner based on the class passed in * * <p>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()) { 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(clazz, classLoader); } } } if (filter == null) { filter = new AnnotationTypeFilter(clazz); } return new AnnotationsScanner(filter); } else { return new InterfaceClassScanner(clazz); } } else { return new ImplementationClassScanner(clazz); } }
public final Annotation[] getDeclaredAnnotations() { return _Type.getDeclaredAnnotations(); }
/** * Tells if a class is deprecated. * * @param type the class to check for deprecation * @return true if the class is deprecated, else false * @since 0.2.05 */ public static boolean deprecated(Class<?> type) { Annotation[] annotations = type.getDeclaredAnnotations(); for (Annotation annotation : annotations) if (annotation instanceof Deprecated) return true; return false; }
@SuppressWarnings("rawtypes") @Test public void searchAndTest() { Reflections reflections = new Reflections("org.estatio.dom"); System.out.println("EstatioDomainObjectContractTestAll_jdoAnnotations"); Set<Class<? extends UdoDomainObject>> subtypes = reflections.getSubTypesOf(UdoDomainObject.class); for (Class<? extends UdoDomainObject> subtype : subtypes) { if (subtype.isAnonymousClass() || subtype.isLocalClass() || subtype.isMemberClass() || subtype.getName().endsWith("ForTesting")) { // skip (probably a testing class) continue; } if (UdoDomainObject.class == subtype || EstatioDomainObject.class == subtype) { // skip continue; } System.out.println(">>> " + subtype.getName()); // must have a @PersistenceCapable(identityType=...) annotation final PersistenceCapable persistenceCapable = subtype.getAnnotation(PersistenceCapable.class); assertThat( "Class " + subtype.getName() + " inherits from EstatioDomainObject " + "but is not annotated with @PersistenceCapable", persistenceCapable, is(not(nullValue()))); IdentityType identityType = persistenceCapable.identityType(); assertThat( "Class " + subtype.getName() + " @PersistenceCapable annotation " + "does not specify the identityType", identityType, is(not(nullValue()))); if (identityType == IdentityType.DATASTORE) { // NOT mandatory to have a @DatastoreIdentity, but if does, then @DatastoreIdentity(..., // column="id") final DatastoreIdentity datastoreIdentity = subtype.getAnnotation(DatastoreIdentity.class); if (datastoreIdentity != null) { assertThat( "Class " + subtype.getName() + " @DataStoreIdentity annotation does not specify column=\"id\"", datastoreIdentity.column(), is("id")); } } Inheritance inheritance = subtype.getAnnotation(Inheritance.class); if (inheritance != null && inheritance.strategy() == InheritanceStrategy.SUPERCLASS_TABLE) { // must NOT have a @Discriminator(..., column="discriminator") final Annotation[] declaredAnnotations = subtype.getDeclaredAnnotations(); for (Annotation declaredAnnotation : declaredAnnotations) { if (declaredAnnotation.annotationType() == Discriminator.class) { Assert.fail( "Class " + subtype.getName() + " inherits from " + subtype.getSuperclass().getName() + "and has (incorrectly) been annotated with @Discriminator"); } } // check if supertype has discriminator // must have a @Discriminator(..., column="discriminator") on one of its supertypes final Discriminator superDiscriminator = subtype.getSuperclass().getAnnotation(Discriminator.class); assertThat( "Class " + subtype.getSuperclass().getName() + " is inherited by " + subtype.getName() + "but is not annotated with @Discriminator", superDiscriminator, is(not(nullValue()))); assertThat( "Class " + subtype.getName() + " @Discriminator annotation does not specify column=\"discriminator\"", superDiscriminator.column(), is("discriminator")); } if (subtype.getSuperclass().equals(UdoDomainObject.class)) { // must have a @Version(..., column="version") final Version version = getAnnotationOfTypeOfItsSupertypes(subtype, Version.class); assertThat( "Class " + subtype.getName() + " inherits from EstatioMutableObject " + "but is not annotated with @Version", version, is(not(nullValue()))); assertThat( "Class " + subtype.getName() + " @Version annotation does not specify have column=\"version\"", version.column(), is("version")); } } }
@Override public void init(final Object object) { if (!(object instanceof StartupObject)) { return; } final StartupObject startupObject = (StartupObject) object; final AppInfo appInfo = startupObject.getAppInfo(); final ClassLoader classLoader = startupObject.getClassLoader(); final ClassLoaderComparator comparator; if (classLoader instanceof ClassLoaderComparator) { comparator = (ClassLoaderComparator) classLoader; } else { comparator = new DefaultClassLoaderComparator(classLoader); } final WebBeansContext webBeansContext = startupObject.getWebBeansContext(); final AlternativesManager alternativesManager = webBeansContext.getAlternativesManager(); final DecoratorsManager decoratorsManager = webBeansContext.getDecoratorsManager(); final InterceptorsManager interceptorsManager = webBeansContext.getInterceptorsManager(); final AnnotationManager annotationManager = webBeansContext.getAnnotationManager(); for (final EjbJarInfo ejbJar : appInfo.ejbJars) { final BeansInfo beans = ejbJar.beans; if (beans == null) { continue; } if (startupObject.isFromWebApp()) { // deploy only the related ejbmodule if (!ejbJar.moduleId.equals(startupObject.getWebContext().getId())) { continue; } } else if (ejbJar.webapp && !appInfo.webAppAlone) { continue; } // fail fast final StringBuilder errors = new StringBuilder("You can't define multiple times the same class in beans.xml: "); if (addErrors(errors, "alternative classes", beans.duplicatedAlternativeClasses) || addErrors(errors, "alternative stereotypes", beans.duplicatedAlternativeStereotypes) || addErrors(errors, "decorators", beans.duplicatedDecorators) || addErrors(errors, "interceptors", beans.duplicatedInterceptors)) { throw new WebBeansConfigurationException(errors.toString()); } // no more need of errors so clear them beans.duplicatedAlternativeStereotypes.clear(); beans.duplicatedAlternativeClasses.clear(); beans.duplicatedDecorators.clear(); beans.duplicatedInterceptors.clear(); for (final String className : beans.interceptors) { final Class<?> clazz = load(PropertyPlaceHolderHelper.simpleValue(className), classLoader); if (clazz != null) { // TODO: Move check to validation phase if (AnnotationUtil.hasAnnotation(clazz.getDeclaredAnnotations(), Interceptor.class) && !annotationManager.hasInterceptorBindingMetaAnnotation( clazz.getDeclaredAnnotations())) { throw new WebBeansConfigurationException( "Interceptor class : " + clazz.getName() + " must have at least one @InterceptorBindingType"); } if (!interceptorsManager.isInterceptorClassEnabled(clazz)) { interceptorsManager.addEnabledInterceptorClass(clazz); classes.add(clazz); } /* else { don't do it, check is done when we know the beans.xml path --> org.apache.openejb.config.DeploymentLoader.addBeansXmls throw new WebBeansConfigurationException("Interceptor class : " + clazz.getName() + " is already defined"); }*/ } else if (shouldThrowCouldNotLoadException(startupObject)) { throw new WebBeansConfigurationException( "Could not load interceptor class: " + className); } } for (final String className : beans.decorators) { final Class<?> clazz = load(PropertyPlaceHolderHelper.simpleValue(className), classLoader); if (clazz != null) { if (!decoratorsManager.isDecoratorEnabled(clazz)) { decoratorsManager.addEnabledDecorator(clazz); classes.add(clazz); } // same than interceptors regarding throw new WebBeansConfigurationException("Decorator // class : " + clazz.getName() + " is already defined"); } else if (shouldThrowCouldNotLoadException(startupObject)) { throw new WebBeansConfigurationException("Could not load decorator class: " + className); } } for (final String className : beans.alternativeStereotypes) { final Class<?> clazz = load(PropertyPlaceHolderHelper.simpleValue(className), classLoader); if (clazz != null) { alternativesManager.addStereoTypeAlternative(clazz, null, null); classes.add(clazz); } else if (shouldThrowCouldNotLoadException(startupObject)) { throw new WebBeansConfigurationException( "Could not load alternativeStereotype class: " + className); } } for (final String className : beans.alternativeClasses) { final Class<?> clazz = load(PropertyPlaceHolderHelper.simpleValue(className), classLoader); if (clazz != null) { alternativesManager.addClazzAlternative(clazz, null, null); classes.add(clazz); } else if (shouldThrowCouldNotLoadException(startupObject)) { throw new WebBeansConfigurationException( "Could not load alternative class: " + className); } } // here for ears we need to skip classes in the parent classloader final ClassLoader scl = ClassLoader.getSystemClassLoader(); final boolean filterByClassLoader = "true".equals(SystemInstance.get().getProperty(OPENEJB_CDI_FILTER_CLASSLOADER, "true")); final Iterator<String> it = beans.managedClasses.iterator(); while (it.hasNext()) { process(classLoader, it, startupObject, comparator, scl, filterByClassLoader); } final Collection<String> otherClasses = ADDITIONAL_CLASSES.get(); if (otherClasses != null) { final Iterator<String> it2 = otherClasses.iterator(); while (it2.hasNext()) { process(classLoader, it2, startupObject, comparator, scl, filterByClassLoader); } } if (startupObject.getBeanContexts() != null) { // ensure ejbs are in managed beans otherwise they will not be deployed in CDI for (final BeanContext bc : startupObject.getBeanContexts()) { final String name = bc.getBeanClass().getName(); if (BeanContext.Comp.class.getName().equals(name)) { continue; } final Class<?> load = load(name, classLoader); if (load != null && !classes.contains(load)) { classes.add(load); } } } addContainerCdiClasses(classLoader, appInfo, ejbJar); } }
@Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); // 1,Inspecting Classes String sClassName = "android.app.NotificationManager"; try { classToInvestigate = Class.forName(sClassName); // Dynamically do stuff with this class // List constructors, fields, methods, etc. } catch (ClassNotFoundException e) { // Class not found! } catch (Exception e) { // Unknown exception } // 2,Inspecting the Constructors Available Within a Class Constructor[] aClassConstructors = classToInvestigate.getDeclaredConstructors(); for (Constructor c : aClassConstructors) { // Found a constructor c } // 3,Inspecting the Fields Available Within a Class Field[] aClassFields = classToInvestigate.getDeclaredFields(); for (Field f : aClassFields) { // Found a field f } // 2nd of 3 sClassName = "android.content.Intent"; try { classToInvestigate = Class.forName(sClassName); String strNewFieldName = "EXTRA_CHANGED_PACKAGE_LIST"; Field newIn22 = classToInvestigate.getField(strNewFieldName); } catch (ClassNotFoundException e) { // Class not found } catch (NoSuchFieldException e) { // Field does not exist, likely we are on Android 2.1 or older // provide alternative functionality to support older devices } catch (SecurityException e) { // Access denied! } catch (Exception e) { // Unknown exception } // 4,Inspecting the Methods Available Within a Class Method[] aClassMethods = classToInvestigate.getDeclaredMethods(); for (Method m : aClassMethods) { // Found a method m } // 5,Inspecting Inner Classes ; Inspecting Member Modifiers int permissions = classToInvestigate.getModifiers(); if (Modifier.isPublic(permissions)) { // Class is Public } if (Modifier.isProtected(permissions)) { // Class is Protected } if (Modifier.isPrivate(permissions)) { // Class is Private } // 6,Inspecting Class Metadata(annotations) sClassName = "android.widget.AbsoluteLayout"; try { classToInvestigate = Class.forName(sClassName); Annotation[] aAnnotations = classToInvestigate.getDeclaredAnnotations(); for (Annotation a : aAnnotations) { // Found an annotation, use a.toString() to print it out } } catch (ClassNotFoundException e) { // Class not found! } catch (Exception e) { // Handle unknown exception! } }