What is the difference between new
operator and Class.forName(...).newInstance()
? Both of them create instances of a class, and I'm not sure what the difference is between them.
Class. newInstance() throws any exception thrown by the constructor, regardless of whether it is checked or unchecked. Constructor. newInstance() always wraps the thrown exception with an InvocationTargetException .
newInstance() creates a new instance of the class represented by this Class object. The class is instantiated as if by a new expression with an empty argument list. The class is initialized if it has not already been initialized. .
getInstance is the static method often used with the Singleton Pattern in Java. The new keyword actually creates a new object. At some point there must be a new (although there are a few other methods to instantiate new objects) to actually create the object that getInstance returns.
forName("your class name"). newInstance() is useful if you need to instantiate classes dynamically, because you don't have to hard code the class name to create an object.
The new
operator creates a new object of a type that's known statically (at compile-time) and can call any constructor on the object you're trying to create. It's the preferred way of creating an object - it's fast and the JVM does lots of aggressive optimizations on it.
Class.forName().newInstance()
is a dynamic construct that looks up a class with a specific name. It's slower than using new
because the type of object can't be hardcoded into the bytecode, and because the JVM might have to do permissions checking to ensure that you have the authority to create an object. It's also partially unsafe because it always uses a zero-argument constructor, and if the object you're trying to create doesn't have a nullary constructor it throws an exception.
In short, use new
if you know at compile-time what the type of the object is that you want to create. Use Class.forName().newInstance()
if you don't know what type of object you'll be making.
Class.forName("your class name").newInstance()
is useful if you need to instantiate classes dynamically, because you don't have to hard code the class name to create an object.
Imagine a scenario where you load classes dynamically from a remote source. You will know their names but can't import them at compile time. In this case you can't use new
to create new instances. That's (one reason) why Java offers the newInstance()
method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With