Java - loading annotated classes

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

    First answer: Take a look at this project.

    Reflections reflections = new Reflections("org.home.junk");
    Set> 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.

提交回复
热议问题