3

So, the problem sounds like this:

I need to get all classes that have a certain annotation in my project. I have managed to do this without any external libraries ( I literally get all .class files in src folder and check is the class has an annotation). It works fine when I run it locally ( run as java application). When I export my project as .jar and try to run the same class, of course it is not working, as my parser cant find any class. Basically, now I'm trying to get all .class files inside the jar file when running the same jar. Is there any method I can do this without adding another library like reflections ?

Thank you

Iulia Muntianu
  • 145
  • 1
  • 14
  • 1
    possible duplicate http://stackoverflow.com/questions/1429172/how-do-i-list-the-files-inside-a-jar-file – srikanth yaradla Aug 21 '12 at 11:04
  • I actually want to know if there is a way to do it without parsing differently when running locally and when running from .jar, I wanted to know if there is a method to get the classes without treating the cases separately – Iulia Muntianu Aug 21 '12 at 11:05
  • 2
    Is there a specific reason that you don't want to use ready-made libraries? Do you want to read class files from a specific JAR or from the classpath? – Tassos Bassoukos Aug 21 '12 at 11:14
  • I am trying to read class files from the same .jar file I am using to run a class. – Iulia Muntianu Aug 21 '12 at 11:24
  • the problem is that I load the class names and paths but because I am running from jar, the method Class.forName(className) fails – Iulia Muntianu Aug 21 '12 at 11:45

1 Answers1

0

If you really feel the need to reinvent the wheel then 3rd party libraries can still help you since most of them are open source. In particular this is Spring's implementation of a classpath scanner and it utilizes this class to actually find the resources.

If you really want to do it without any differences in the implementation then you one way, as martijno suggested, extract the jar first. However, if the jar isn't on your classpath then you will need something like a URLClassLoader to load the class from the jar.

Another way, is to change your current implementation to scan the classpath. This involves using the ClassLoader.getResources method to find all classes and subpackages in a given package. Then, whether you are using files or a jar all you have to do is get a class loader (e.g. a URLClassLoader) that contains the classes you want (or use the system class loader if they're on the classpath).

Community
  • 1
  • 1
Pace
  • 41,875
  • 13
  • 113
  • 156