Search code examples
javaconstructorclassloader

How to get an instanced Object from an incomplete class name?


world! I need to instantiate an Object from the name of its Class. I know that it is possible to do it, this way

MyObject myObject = null;
try {
    Constructor constructor = Class.forName( "fully.qualified.class.name"  ).getConstructor(); // Get the constructor without parameters
    myObject = (MyObject) constructor.newInstance();
} catch (Exception e) {
    e.printStackTrace();
}       

The problem is that the name of my class is not fully qualified. Is there a way to get the complete name by only knowing the short name?


Solution

  • MyObject myObject = null;
    for (Package p : Package.getPackages()) {
        try {
            myObject = Class.forName(p.getName() + "." + className).newInstance();
            break;
        } catch (ClassNotFoundException ex) {
            // ignore
        } 
    }
    

    The Package.getPackages() call will give you every package known to the current classes ClassLoader and its ancestors.

    Warning: this will be expensive because you are repeatedly throwing and catching exceptions. It may be possible to speed it up by testing:

    this.getClass().getClassLoader().findResource(binaryClassName) != null
    

    before calling Class.forName(...) or the equivalent.