Question

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.

Was it helpful?

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.

OTHER TIPS

You need to understand that the meaning of a class name like "Person" depends on where it occurs in the source code. It is a convenience of the Java compiler to not require fully qualified class names everywhere. But at runtime, in byte code, all class names are fully qualified.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top