0

I am using google Reflections in a java library I am developing. The reason I use Reflections is because I want to find all the classes with a particular annotation. Simplifying things, in my library I have a method answering those classes, that is invoked with a line like:

//this method uses the Reflections library
Repository.getDefault().getMyAnnotatedClasses()

In the current version of my library, I require the user to explicitly add the package name where the Reflections library need to look for the annotated classes:

Repository.getDefault().addSearchPath("...");

In this way Reflections will look for classes located only in that package.

If the user of my library does not add this search path, I configure Reflections to search in all the classes in the system class loader. Obviously this solution is quite inefficient. However, I really want to get rid of the requirement of asking the user to ALWAYS set the search path. - A side note in case it is important: in Reflections you can configure a search path with a package name, a url (the classpath where the classes can be found), or a class loader.

So my question is: Is there a way to find the classpath of the class invoking my library ? (from my library code). In this way, I could detect that if the user has not explicitly set a search location, I will add that location by default, which seems to be a better solution than adding the entire system class loader as the alternative search path.

I know I could manually inspect the method call stack from my library code, but this seems a bit of a hack and dirty solution, so I am looking for alternative ideas.

Thanks in advance.

Sergio
  • 8,532
  • 11
  • 52
  • 94

1 Answers1

0

You can find the caller of a method by analyzing the stacktrace. Although not a good idea in general IMHO as it breaks encapsulation and sensitive to managed environments (proxies and so), it will work. Look more in this question.

What else you can do, and avoid the inefficiency of scanning all classpath every time, is to scan and save once on compile time with reflections, and than collect it on bootstrap time.

To scan and save once as XML:

new Reflections(...).save([somepath]);

And than collect without scanning:

Reflections reflections = Reflections.collect([somepath]);

If you're using Maven, you can automate it and do it as part of every build using the Reflections-Maven plugin.

Look for more info at collect pre scanned metadata in the Reflections UseCases Wiki page

Community
  • 1
  • 1
zapp
  • 1,533
  • 1
  • 14
  • 18