Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 423
tunnuz Avatar asked Dec 07 '25 02:12

tunnuz


2 Answers

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.

like image 133
Stephen C Avatar answered Dec 08 '25 15:12

Stephen C


Try this repeatedly for a package search path. ;)

String[] packages = ...;
String className = ...;
MyObject myObject = null;
for(String p : packages)
  try {
    myObject = Class.forName(p + '.' + className).newInstance();
    break;
  } catch (Exception ignored) {
  } 
like image 25
Peter Lawrey Avatar answered Dec 08 '25 15:12

Peter Lawrey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!