Java - 加载带注释的类 [英] Java - loading annotated classes

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

问题描述

我知道有很多令人难以置信的工具可以在 Java 中加载插件类,但今天我想到了一个想法.

如果我在包org.home.junk"中有一堆注释和未注释的类(用注释@AnnotatedClass"注释)并且这些类有注释的方法,说注释@AnnotatedMethod".

第一个问题:我能否在运行时获取该特定包中所有类的数组/集合,以便我可以检查哪些类被注释并创建它们的实例.(但是我知道如何检查 Some.class 是否有本指南提供的注释:http://isagoksu.com/2009/development/java/creating-custom-annotations-and-making-use-of-them/)

第二个问题: - 如果我可以在第一个问题中做我想做的事情 - 最政治化的方式是什么?

我相信这是可能的,因为我了解 JUnit 以某种类似的方式加载测试用例类.

此外,如果可以使用最少的第三方库等来完成此操作也会很酷 - 如果可能的话:)

解决方案

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

Reflections 反射 = new Reflections("org.home.junk");设置<类<?>>注释 = 反射.getTypesAnnotatedWith(javax.persistence.Entity.class);

它返回用 javax.persistence.Entity 注释注释的 org.home.junk 中的所有类.

第二个答案:要创建上述类的新实例,您可以这样做

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

希望这能回答一切.

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

解决方案

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.

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

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