How do I get the class canonical name by its simple name?

386 Views Asked by At

Given I have a string with a simple class name:

String className = "myClassName";

and I know for sure there is a class with this name somewhere under:

"com.automation.qa.company.tests...."

How can I get the canonical name for this class? Please help me find the best solution in Java.

1

There are 1 best solutions below

9
On

Create a method that adds the possible package names to the under specified class name, and then checks to see if it can load the class using Class.forName(...).

Below is an example that will search all the Packages accessible by the current class loader. You might want to put a filter into it to keep the search for your class only under a specific part of the accessible packages.

public String findClass( String shortName) {
  for (Package pack : Package.getPackages()) {
    try {
      String resolvedName = pack.getName() + "." + className;
      Class class = Class.forName(resolvedName);
      return resolvedName;
    } catch (ClassNotFoundException e) {
      // intentionally blank
    }
  }
  return null;
}