goraccio
goraccio

Reputation: 21

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

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.

Upvotes: 0

Views: 441

Answers (1)

Edwin Buck
Edwin Buck

Reputation: 70999

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;
}

Upvotes: 0

Related Questions