简体   繁体   中英

Dynamically loading a class in Java

I looked up the syntax and searched the api but am still confused about the process. I also searched Stackoverflow. What is the proper way to load a class and create an object out of it dynamically? In otherwords I want the user to specify what type of object they want to create, and then create that type of object. I don't want a menu, because I want them to be able to choose any class within the current directory.

Assuming the class has no-arg constructor, the simplest way would be -

Object newObject = Class.forName(strFullyQualifiedClassName).newInstance();

Reference - java.lang.Class

ClassLoader.loadClass will load a class. You get a classloader by myClass.getClassLoader() and you should fall back to ClassLoader.getSystemClassLoader() if that is null.

Once you've got a class instance, you can get its constructors via getDeclaredConstructor(...) . So if you have a public class MyClass with a constructor like public MyClass(String) { ... } then

Class<MyClass> clazz = MyClass.class;
Constructor<MyClass> ctor = clazz.getDeclaredConstructor(String.class);
MyClass instance = ctor.newInstance("foo");

The above ignores a bunch of possible exceptions.

Here is what I got working. This is not a finihsed product, but is just test to see if I could get it to work. Thank you to everyone that answered the questoin :-).

public class SimLoader {  
  public static void main(String[] args)  
  {  
    try  
    {  
    Object simulator = Class.forName("SimX").newInstance();  
    ((SimInterface)simulator).run();  
    }  
    catch(ClassNotFoundException e) {}  
    catch(InstantiationException e) {}  
    catch(IllegalAccessException e) {}  
    }  
  }  
interface SimInterface {  
 void run();  
}  
class SimX implements SimInterface  
{  
  public void run() {  
    System.out.println("Success");  
  }  
}  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM