爪哇 - 加载注释类 [英] Java - loading annotated classes

查看:179
本文介绍了爪哇 - 加载注释类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道有令人难以置信的一套Java中加载插件类的工具,但今天一个想法来到了我的脑海里。

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

如果我有一堆包org.home.junk注释和未标注类(有标注@AnnotatedClass注明)和那些类有注解的方法与注释说@AnnotatedMethod。

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".

第一个问题:我在运行时得到的所有类的数组/集合在特定的包,这样我可以检查哪一个的被注释和创建它们的实例。 (我知道但是如何检查Some.class在本指南的注释提供:<一href=\"http://isagoksu.com/2009/development/java/creating-custom-annotations-and-making-use-of-them/\">http://isagoksu.com/2009/development/java/creating-custom-annotations-and-making-use-of-them/)

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?

我相信这是可能的,据我了解的JUnit载荷一些类似方式的测试用例类。

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 :)

推荐答案

第一个答案:看看的这个项目

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

它返回从 org.home.junk 所有类与 javax.persistence.Entity 注解。

第二个答案::要创建上面的类新实例,你可以做到这一点。

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.

这篇关于爪哇 - 加载注释类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆