0

If I'm provided an address to a directory, but I have no information regarding what is within the directory, can I check to see if the directory contains any classes and access the classes via URLClassLoader.

I'm currently creating a URL array with the address of the directory:

URL [] urls = new URL[1];
urls[0] = new File(address).toURI().toURL();
URLClassLoader urlClassLoader = new URLClassLoader(urls);

However, even with this approach, I can't access classes from the URLClassLoader object since I don't know what the classes are called, right?

Brosef
  • 2,945
  • 6
  • 34
  • 69
  • 2
    How about [walking the file tree](https://docs.oracle.com/javase/tutorial/essential/io/walk.html) and load each ".class" file you find? – D.B. Nov 13 '17 at 02:02
  • You are correct that Java intentionally does not provide a way to enumerate the classes in a package. There is a Guava utility that peeks into the loader, gets the directory, and enumerates the .class files for you. – bmargulies Nov 13 '17 at 02:02
  • I’m not sure why you need this, but I suspect you would be better served by having discoverable classes implement an interface, and making that interface a service provider interface, as described in the [ServiceLoader documentation](https://docs.oracle.com/javase/9/docs/api/java/util/ServiceLoader.html). – VGR Nov 13 '17 at 23:56

1 Answers1

0

The closest thing you are likely to get is The Guava ClassPath class. However, this works by peeking into the URLClassLoader and then talking to the file system.

bmargulies
  • 97,814
  • 39
  • 186
  • 310