Reputation: 46492
I want to list some classes on the classpath, but I don't want all of them (moreover, scanning the whole classpath is pretty slow). Given a single ExampleClass
, I want to get all classes residing in the same classpath entry (i.e., directory or JAR, other cases can be ignored). There's a single ClassLoader.
Using ExampleClass.class.getResource("/")
does not work as I always get the first classpath entry, e.g.,
/whatever/build/classes/main/
ExampleClass.class.getResource(".")
returns a child of the proper entry, e.g.,
/whatever/build/classes/test/somepackage/ExampleClass.class
which is something I could process to
/whatever/build/classes/test/
But I wonder if there's a better way than fooling around with strings.
Upvotes: 0
Views: 39
Reputation: 109613
URL url = ExampleClass.getProtectionDomain().getCodeSource().getLocation();
Check for null however.
Upvotes: 2
Reputation: 653
Here is an example:
package foo;
public class Test
{
public static void main(String[] args)
{
ClassLoader loader = Test.class.getClassLoader();
System.out.println(loader.getResource("foo/Test.class"));
}
}
Output is:
file:/C:/Users/Jon/Test/foo/Test.class
Upvotes: 0