Friday, August 23, 2013

Java reflection libraries: Reflections vs Guava-reflection

Recently I have been working on my new open source tool: Autodoc .
A feature I needed for it to work was to get all classes in a given package, to analyze them one by one.
Searching for a solution I found out it's not a trivial task in Java, so I looked for a library to get the list I needed.

First try: Reflections

My first try was of course the very well known Reflections library; it's quite easy to use and well documented.
It worked like a charme for my test classes, but it failed miserably in the tests I did on some live projects...
The point is that Reflections will filter only classes with a specific annotation or direct subclasses of a given class! In my tool I couldn't put any constraint about common superclass or use of a specific annotation, so I had to find another library.

Saved by Guava-reflection

I looked further and found a library which seems perfect for my uses: Guava-reflection.
Guava is an impressive collection of useful utility methods and classes, and in particular the Classpath class seemed able to do the trick.
It seems simpler and less powerful than Reflections but it just lists all classes in a package and can do it recursively if needed; the code is very simple:
ClassPath classpath = ClassPath.from(Thread.currentThread()
.getContextClassLoader());
for (ClassPath.ClassInfo classInfo : classpath
.getTopLevelClassesRecursive(packagetoParse)) {
// do whatever I need with class info
}


Final words

I think both libraries are very good, so I won't throw Reflections away, it could always come in handy later or on different projects. I think it's always better to have a look at both libraries before giving up and rolling out a new implementation (which will take much time and most probably won't be any better!)

No comments:

Post a Comment