Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use ClassLoader.getResources() correctly? [duplicate]

How can I use ClassLoader.getResources() to find recursivly resources from my classpath?

E.g.

  • finding all resources in the META-INF "directory": Imagine something like

    getClass().getClassLoader().getResources("META-INF")

    Unfortunately, this does only retrieve an URL to exactly this "directory".

  • all resources named bla.xml (recursivly)

    getClass().getClassLoader().getResources("bla.xml")

    But this returns an empty Enumeration.

And as a bonus question: How does ClassLoader.getResources() differ from ClassLoader.getResource()?

like image 658
MRalwasser Avatar asked Mar 04 '11 12:03

MRalwasser


People also ask

How does ClassLoader getResource work?

getResource() method finds the resource with the given name. A resource is some data (images, audio, text, etc) that can be accessed by class code in a way that is independent of the location of the code. The name of a resource is a '/'-separated path name that identifies the resource.

What is ClassLoader in Java with example?

The Java ClassLoader is a part of the Java Runtime Environment that dynamically loads Java classes into the Java Virtual Machine. The Java run time system does not need to know about files and file systems because of classloaders. Java classes aren't loaded into memory all at once, but when required by an application.

How does getResource work in Java?

The getResourceAsStream method returns an InputStream for the specified resource or null if it does not find the resource. The getResource method finds a resource with the specified name. It returns a URL to the resource or null if it does not find the resource. Calling java.

What is the difference between class getResource () and ClassLoader getResource ()?

Class. getResources would retrieve the resource by the classloader which load the object. While ClassLoader. getResource would retrieve the resource using the classloader specified.


1 Answers

The Spring Framework has a class which allows to recursively search through the classpath:

PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); resolver.getResources("classpath*:some/package/name/**/*.xml"); 
like image 61
rec Avatar answered Sep 24 '22 13:09

rec