Is it possible to find all classes annotated with @MyAnnotation using the GWT GeneratorContext?

When creating classes using Generators, you can find all subclasses of the type. You can find this technique, for example, in the source of the GWT Showcase (see full code ):

JClassType cwType = null; try { cwType = context.getTypeOracle().getType(ContentWidget.class.getName()); } catch (NotFoundException e) { logger.log(TreeLogger.ERROR, "Cannot find ContentWidget class", e); throw new UnableToCompleteException(); } JClassType[] types = cwType.getSubtypes(); 

I would like to do something similar, but instead of extending the class (or implementing the interface)

 public class SomeWidget extends ContentWidget { ... } 

can i do this by adding annotations to widgets?

 @MyAnnotation(...) public class SomeWidget extends Widget { ... } 

And then find all widgets that are annotated with @MyAnnotation? I could not find a method like JAnnotationType.getAnnotatedTypes() , but maybe I'm just blind?

Note. I managed to get it to work with the Google Reflections library using reflections.getTypesAnnotatedWith(SomeAnnotation.class) , but I would rather use GeneratorContext instead, especially because it works much better when reloading the application in DevMode.

+6
source share
1 answer

Yes. The easiest way is to loop over all types and check them for annotation. You may have other rules (public, not abstract) that must also be followed at this time.

 for (JClassType type : oracle.getTypes()) { MyAnnotation annotation = type.getAnnotation(MyAnnotation.class); if (annotation != null && ...) { // handle this type } } 

A TypeOracle instance can be obtained from GeneratorContext using context.getTypeOracle() .

Note that this will give you access to the types of the source path. That is, only the types currently available based on the inherited modules and the <source> tags used are available.

+8
source

Source: https://habr.com/ru/post/915305/


All Articles