Java - loading annotated classes

后端 未结 4 1970
生来不讨喜
生来不讨喜 2020-12-14 16:51

I know there are incredible set of tools for loading plugin classes in java, but today an idea came to my mind.

What if I have a bunch of annotated and un-annotated

4条回答
  •  时光取名叫无心
    2020-12-14 17:35

    It can be done with techniques that check the filesystem because it is more a classloader issue than a reflection one. Check this: Can you find all classes in a package using reflection?.

    If you can check all the class files that exists in a directory, you can easily get the corresponding class using this method

    Class klass = Class.forName(className)
    

    To know if a class is annotated or not is a reflection issue. Getting the annotations used in a class is done this way:

    Annotation[] annotations = klass.getAnnotations();
    

    Be sure to define your custom annotation with a retention policy type visible at run time.

    @Retention(RetentionPolicy.RUNTIME) 
    

    This article is a good resource for more info on that: http://tutorials.jenkov.com/java-reflection/annotations.html.

提交回复
热议问题