Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
405 views
in Technique[技术] by (71.8m points)

annotations - Java - loading annotated classes

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 classes in package "org.home.junk" (annotated with annotation "@AnnotatedClass") and those classes have annotated methods with say annotation "@AnnotatedMethod".

First question: can I at run-time get an array/collection of all the classes in that specific package, so that I could check which one's are annotated and create an instance of them. (I am aware however how to check if Some.class has annotations courtesy of this guide: http://isagoksu.com/2009/development/java/creating-custom-annotations-and-making-use-of-them/)

Second question: - If I can do what I'd like in first question - what would be the most political way to do this?

I believe it is possible, as I understand JUnit loads test-case classes in some similar manner.

Also it would be cool if this could be done with minimal third party libraries and such, again - if it's possible :)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...