4

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.

Marquinio
  • 4,601
  • 13
  • 45
  • 68
  • 2
    What if there was also a thirdpckg.Person, fourthpckg.Person, etc class. What if there was a Person class in the unnamed package. – emory Apr 26 '12 at 21:59
  • You might scan your entire classpath (it's a list of directories and jar files, essentially) and look for a file named like your class. Then you'll have the package name from its path name. You may end up with many matching files, though. – 9000 Apr 26 '12 at 22:02
  • We will not allow duplicate class names. These will just be unique class names. – Marquinio Apr 26 '12 at 22:04
  • I guess you got the simple name by user input? then you could search the certain directory for the file, in this case, Person.class in FS. (you know which directory you are gonna look for, don't you?) then convert the path to Person.class into "package.subpackage.Person", finally load the class. – Kent Apr 26 '12 at 22:04

2 Answers2

4

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.

Community
  • 1
  • 1
Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
  • 1
    +1 - *"Note that the same name can be used in multiple packages."* ... and therefore that you need a strategy for dealing with the case where there are multiple classes with the same (simple) name. I also agree strongly that this is not a good design. – Stephen C Apr 26 '12 at 22:57
1

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.

Ingo
  • 36,037
  • 5
  • 53
  • 100