Java - loading annotated classes

后端 未结 4 1957
生来不讨喜
生来不讨喜 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:25

    It all depends on what kind of requirement you have for annotation.

    Like e.g. @EJB : This annotation is designed so that container will identify and do EJB Specific work which requires scanning through files and then finding such classes.

    However if your requirement is only to enable specific functionality based on annotation then you can do it using java reflection only

    e.g. @NotNull : This annotation is designed in JSR 303 to verify that Annotated element is not null. This functionality can be easily implemented at run time using reflection API

    0 讨论(0)
  • 2020-12-14 17:26

    First answer: Take a look at this project.

    Reflections reflections = new Reflections("org.home.junk");
    Set<Class<?>> annotated = reflections.getTypesAnnotatedWith(javax.persistence.Entity.class);
    

    It returns all the classes from org.home.junk annotated with javax.persistence.Entity annotation.

    Second Answer: To create new instance of above classes you can do this

    for (Class<?> clazz : annotated) {
        final Object newInstance = clazz.newInstance();
    }
    

    Hope this answers everything.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-14 17:38

    If you have Spring(3rd party, sorry :-)), use the org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider

    A code usage example can be found in this SO question

    0 讨论(0)
提交回复
热议问题