Sharing the difference between new keyword and newInstance method in Java

  • 2020-04-01 02:05:35
  • OfStack

NewInstance () USES the classloading mechanism, and new is to create a new class.
From the JVM's perspective, when a class is created with new, it can be unloaded. But when you use the newInstance () method, you have to make sure that the class is loaded and connected.


String className="test";
Class c=Class.forName(className); 
factory=(ExampleInterface)c.newInstance();

NewInstance (): if the type. Low efficiency, can only call the parameter - free construction method, suitable for factory mode;

New: strongly typed. Relatively efficient. Any public constructor can be called


Related articles: