1

I get that you can run a method on classloading by using a static initializer.

The challenge is waiting for the classloader to load the class.

Assume my class to load is Initializer. (No package).

You can trigger the classloader to load the class with a line like:

Initializer.class.getName();

But if you use a line like:

Initializer obj;

Then the classloader is not run.

ie by default, the classloader is not run for classes on the classpath. They have to be on the path of execution.

My question is: Is there a way for a class to trigger it's own classloading without being on the path of execution of a program?

The broader goal is to be able to drop a jar into an existing project, without modifying the original project, and have the extra method in the jar run on application startup.

hawkeye
  • 34,745
  • 30
  • 150
  • 304
  • could you be more precise ? what is the goal ? You finally want to use a classloader to load it ? (like obj=new Initializer() ?) And you want to use a custom one ? Or you just to load the class ? – guillaume girod-vitouchkina Dec 27 '15 at 12:51
  • Cool thanks - updated. – hawkeye Dec 27 '15 at 12:55
  • You'll probably want an actual plugin architecture of some sort instead of relying on the classloader. I'm fairly sure a classloader is meant to do what the name suggests - load classes as needed, not handle autodiscovery of components. Start with some sort of classpath scanner, last time I tried to do this was years ago, but Google found me this which looks usable: https://github.com/lukehutch/fast-classpath-scanner – millimoose Dec 27 '15 at 13:07
  • 2
    You can achieve what you want with a service provider. Tutorial here: https://docs.oracle.com/javase/tutorial/ext/basics/spi.html – JB Nizet Dec 27 '15 at 13:08

0 Answers0