Search code examples
javaclassclassloaderdynamic-class-loaders

How to load a Class using only the class name


I need to use Java's Class.forName("") to load one of my classes. Problem is that I need to load the class by only specifying the class name and NOT the fully qualified class name.

  1. For example this works but doesn't fit my requirements:

    Class.forName("reflection.Person");

  2. And this is what I need but is not working:

    Class.forName("Person");

Anyone knows how to get #2 working? I just need to use the simple class name. Any 3rd party tools that will walk through my folder structure to check if the class exists? This will be deployed as an executable JAR.

Thanks in advance.


Solution

  • You should get all classes on the classpath, iterate them and see which one has a simple name that is equal to the desired one. Then do Class.forName(..) with the fully-qualified name. Note that the same name can be used in multiple packages.

    You'd better look for classes implementing an interface or annotated with a specific annotation. Relying on the simple name can be really tricky, especially if your classpath grows.