Search code examples
javajakarta-eeclassloader

How to load a class without referring to it?


I am using Java 6.

I have static block in one of my class say "MyStaticBlockClass.java".

There are no references to that class (MyStaticBlockClass.java) from the rest of my project.

Here I need to execute the static block in the above specified class at the time of JVM start up.

Is there a way to load the class into JVM without references to that class ?


Solution

  • You could use Class.forName("your.pkg.MyStaticBlockClass"). That was how JDBC used to work - the static initializer in the driver class would register itself as being capable of handling specific URLs.

    Now, that mechanism was superceded by DriverManager discovering drivers in all kinds of other ways. You should consider whether some of those techniques would be appropriate in your situation too - in general, relying on a static initializer having executed feels like a code smell. It may not be, but it's worth at least thinking about alternative designs.