工作中配合Google Guice的使用,用到了Reflections工具包,记录一下,备忘。
项目地址:
http://code.google.com/p/reflections/
从官方文档上,我们可以了解到它是一个用于Java运行时元数据分析,本着注解搜寻的精神。
用途:
Reflections scans your classpath, indexes the metadata, allows you to query it on runtime and may save and collect that information for many modules within your project.
Using Reflections you can query your metadata such as:
get all subtypes of some type
get all types/methods/fields annotated with some annotation, w/o annotation parameters matching
get all resources matching matching a regular expression
UseCases:
some useful use cases below:
bootstrap in a multi module environment
collect pre scanned metadata
serialize Reflections into a java source file, and use it to statically reference java elements
query the store directly, avoid definition of types in class loader
find resources in your classpath (for example all properties files)
optional parallel scanning
bootstrap in a multi module environment
In a multi module project, where each module is responsible for it's properties, jpa entities and maybe guice modules, use Reflections to collect that metadata and bootstrap the application
Reflections reflections = new Reflections(new ConfigurationBuilder()
.addUrls(ClasspathHelper.forPackage("your.package.here"),
ClasspathHelper.forClass(Entity.class),
ClasspathHelper.forClass(Module.class))
.setScanners(new ResourcesScanner(),
new TypeAnnotationsScanner(),
new SubTypesScanner()));
Set<String> propertiesFiles = reflections.getResources(Pattern.compile(".*\\.properties"));
Properties allProperties = createOneBigProperties(propertiesFiles);
Set<Class<?>> jpaEntities = reflections.getTypesAnnotatedWith(Entity.class);
SessionFactory sessionFactory = createOneBigSessionFactory(jpaEntities, allProperties);
Set<Class<? extends Module>> guiceModules = reflections.getSubTypesOf(Module.class);
Injector injector = createOneBigInjector(guiceModules);
collect pre scanned metadata
first configure your project's parent pom in the build.plugins section with Reflections, like this
<plugin>
<groupId>org.reflections</groupId>
<artifactId>reflections-maven</artifactId>
<version>0.9.8</version>
<executions>
<execution>
<goals>
<goal>reflections</goal>
</goals>
<phase>process-classes</phase>
</execution>
</executions>
</plugin>
than, on runtime, collect these pre saved metadata and instantiate Reflections
Reflections reflections =
isProduction() ? Reflections.collect() : new Reflections("your.package.here");
of course, saving the scanned metadata can be done without maven, by simply calling the save method
public static void main(String[] args) {
//from time to time, I run this main to regenerate saved metadata for Reflections
new Reflections(new ConfigurationBuilder()
.setUrls(ClasspathHelper.forPackage("my.project.prefix"))
.setScanners(/*whatever*/))
.save("src/main/resources/resource1-reflections.xml");
new Reflections(new ConfigurationBuilder()
.setUrls(ClasspathHelper.forPackage("my.project.prefix.model"))
.filterInputsBy(new FilterBuilder().include(FilterBuilder.prefix("my.project.prefix.model")))
.setScanners(new TypesScanner(), new TypeElementsScanner())
.setSerializer(new JavaCodeSerializer()))
.save("src/main/java/my.project.prefix.model.MyModelStore");
}
serialize Reflections into a java source file, and use it to statically reference java elements
Reflections reflections = new Reflections(new ConfigurationBuilder()
.filterInputsBy(new FilterBuilder().include("model.package"))
.setScanners(new TypesScanner(), new TypeElementsScanner())
.setUrls(asList(ClasspathHelper.forPackage("model.package"))));
String filename = System.getProperty("user.dir") + "/src/test/java/model.package.reflections.MyModelStore";
reflections.save(filename, new JavaCodeSerializer());
replace "model.package" with your model's package prefix
this serializes types and types elements into interfaces respectively to fully qualified name, for example:
//generated using Reflections JavaCodeSerializer
public interface MyTestModelStore {
public interface org extends IPackage {
public interface reflections extends IPackage {
public interface TestModel$AC1 extends IClass {}
public interface TestModel$C4 extends IClass {
public interface f1 extends IField {}
public interface m1 extends IMethod {}
...
}
than use the different resolve methods to resolve the serialized element into Class, Field or Method. for example:
Class<? extends IMethod> imethod = MyTestModelStore.org.reflections.TestModel$C4.m1.class;
Method method = JavaCodeSerializer.resolve(imethod);
can be useful to represent ognl statically and not in by strings or to use in annotations for marking fields or methods in a static manner
query the store directly, avoid definition of types in class loader
querying through Reflections results in classes defined by the class loader. this is usually not a problem, but in cases class definition is not desirable, you can query the store directly using strings only
Reflections reflections = new Reflections(...); //see in other use cases
Set<String> serializableFqns = reflections.getStore().getSubTypesOf("java.io.Serializable");
plus, you can create your specialized query methods by querying the store directly
Map<String, Multimap<String, String>> storeMap = reflections.getStore().getStoreMap();
//or
Multimap<String, String> scannerMap = reflections.getStore().get(ResourcesScanner.class);
find resources in your classpath
Reflections reflections = new Reflections(new ConfigurationBuilder()
.setUrls(ClasspathHelper.forPackage("your.package.here"))
.setScanners(new ResourcesScanner());
Set<String> propertiesFiles = reflections.getResources(Pattern.compile(".*\\.properties"));
Set<String> hibernateCfgFiles = reflections.getResources(Pattern.compile(".*\\.cfg\\.xml"));
optional parallel scanning
Reflections reflections = new Reflections(new ConfigurationBuilder()
.filterInputsBy(...)
.setScanners(...)
.setUrls(...)
.setExecutorService(Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()));
will result in this log line when scanning:
[main] INFO org.reflections.Reflections - Reflections took 164 ms to scan 1 urls, producing 13 keys and 23 values [using 2 cores]
分享到:
相关推荐
总结来说,"reflections.zip"是一个用于动态发现和查询Java项目中类路径元数据的开源工具。它通过反射技术扫描类路径,建立元数据索引,方便在运行时查询和使用。开源的性质使得开发者可以深入研究其工作原理,并...
本文将深入探讨PIDI - Planar Reflections这一工具,以及如何在Unity3D项目中有效地利用它。 平面反射技术,顾名思义,是通过在平面上捕捉并映射周围环境的反射,来模拟真实世界中物体表面反射的现象。在Unity3D中...
在`findbugs-jmock`的压缩包`reflections-maven-2.0.Beta2.zip`中,包含了`findbugs-jmock-master`这一子目录,这通常是源代码仓库的主分支,包含了项目的源代码、构建脚本和其他相关资源。开发者可以克隆或下载这个...
在项目中引入依赖后,我们可以创建一个`Reflections`对象,传入扫描的基础包名: ```java Reflections reflections = new Reflections("com.myproject"); ``` 接着,我们可以通过`getTypesAnnotatedWith`方法来...
对于那些需要频繁使用反射和注解的项目来说,`reflections-utils`无疑是一个值得考虑的工具。 总结一下,`reflections-utils`是一个针对Java反射和注解的实用库,它提供了一系列便利的API,帮助开发者更高效地进行...
在IT行业中,"reflections"通常指的是Java编程语言中的反射机制。反射是Java提供的一种强大的工具,它允许程序在运行时检查和修改自身的结构和行为。这个机制在很多场景下非常有用,比如在框架开发、元数据处理、...
- 初始化:创建一个Reflections实例,指定扫描的基包或类路径。 - 扫描:通过调用` Reflections.scan()`或`Reflections.collect()`进行扫描。 - 查询:使用`Reflections.getSubTypesOf()`, `Reflections....
这个工具包可能包含了各种水体效果,如海洋、湖泊、河流等,旨在提升游戏环境的真实感和沉浸感。Unity是一款广泛应用于游戏开发、虚拟现实(VR)、增强现实(AR)等领域的跨平台游戏引擎,其强大的3D渲染和物理模拟...
7. **反射工具类**:如Java的java.lang.reflect包,或Google的Reflections库,用于运行时检查和操作类、接口、字段和方法。 8. **编码解码工具类**:如Base64编码解码,可以在Java 8的java.util.Base64中找到,或者...
这篇文章将向大家分享如何使用 Java 反射机制和第三方工具包 org.reflections 来实现动态获取实现某个接口下所有的实现类对象集合。 首先,为什么我们需要动态获取实现某个接口下所有的实现类对象集合?在实际开发...
Java 8引入的`java.time`包提供了更强大的日期时间API,而`TimeUtils` 可能是对这些API的封装,提供了更简洁的调用方式。 以上就是这些Java工具类的基本介绍,它们覆盖了文件操作、数据库交互、身份证处理、配置...
动态图片,通常指的是GIF格式的图像,它能够在单一文件中包含多帧图像...通过 Sqirlz Water Reflections 这样的工具,无论是为了娱乐还是专业用途,任何人都能轻松踏入动态图像的创作世界,制作出引人注目的动态图片。
类图扫描库,如`org.reflections.jar`,提供了在运行时动态发现和分析类的能力。这可以帮助开发者在不修改代码的情况下,找到类之间的依赖关系,或者在框架中自动注册组件。 4. **其他辅助库**:Java生态系统中有...
4. **Classpath scanning**:通过工具或自定义代码扫描`Classpath`,寻找特定类,例如使用`Class.forName()`或第三方库如`Reflections`。 5. **模块系统**:Java 9引入了模块系统,使用`module-info.java`文件来...
根据提供的压缩包子文件的文件名称“Sqirlz Water Reflections V2.3 圖片水波紋制作(免裝版)”,我们可以推测这个软件名为“Sqirlz Water Reflections”,版本为V2.3,是一款专注于图片水波纹效果制作的工具,并且是...
2. **初始化Reflections**:通过`Reflections`类,我们可以指定要扫描的包名(如"org","javax","com","io"),这将涵盖大部分主流开源库。然后,我们可以获取这些库中的所有子类。 3. **统计命名频率**:遍历获取到...
Unity引擎是一款广泛应用于游戏开发、虚拟现实和增强现实领域的3D和2D图形渲染工具。在Unity中,射线反射是一种关键的技术,用于模拟光线在物体表面的反射效果,为场景带来更真实的视觉体验。本资源包专注于讲解射线...
Sqirlz Water Reflections是一款专门用来制作水波纹效果的软件,它可能包含了一系列易于使用的工具和预设选项,让用户可以自定义水波的强度、频率、方向等参数,以达到理想的效果。此外,汉化版意味着所有菜单、提示...