i2ijeya
i2ijeya

Reputation: 16430

What is the difference between the new operator and Class.newInstance()?

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.

Upvotes: 38

Views: 34072

Answers (10)

templatetypedef
templatetypedef

Reputation: 373402

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.

Upvotes: 64

Kanchan Kumar
Kanchan Kumar

Reputation: 1

Let's assume com.statckoverflow.Test

Class.forName - It will load the Test class and return the Class class object which contains the metadata of Test class Like name, package, constructor, annotations, methods, fields.

newInstance() - Used to instantiate new objects using Java Reflection. Internally zero parameter constructor will be called on the Test class. This means Class class object will create the Test class object by calling the zero parameter constructor, We can use the reflection for details of Test class. Like Constructors, methods etc.

new operator - Creates the New Object for the class instantiate the Class and can call their constructors.

Upvotes: 0

Andreas Dolk
Andreas Dolk

Reputation: 114817

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.

Upvotes: 16

Zeki
Zeki

Reputation: 5296

Class.forName will do a lookup to find the Class object for YourClass.

Using the new operator should be the same as YourClass.class.newInstance().

Upvotes: 1

E A
E A

Reputation: 1254

Class.forName("your class name").newInstance() is used when you want to get an instance form a class work similar to new, but it is useful when you want to get instance from a class in a jar file or remote server and you can not import it in compile time.

ex: Class.forName("YOUR JDBC DRIVER").newInstance(), you can not import the JDBC class at compile time.

Upvotes: 3

Nipuna
Nipuna

Reputation: 7026

Class.forName('myClass').newInstance() loads the class if not already loaded. Here it calls the initial constructor and only executes the static part of the constructor.

The new operator is used to initialize new objects.

You can create many instances from both the new operator and Class.forName() difference is the 2nd time you create a newInstance() static blocks will not get initialized.

A good example of Class.forName('myClass).newInstance() is the JDBC driver

Class.forName("com.mysql.JDBC.Driver").newInstance()

Upvotes: 2

fastcodejava
fastcodejava

Reputation: 41117

The major difference is Class.forName('your class name').newInstance() is dynamic as type need not be hard coded into the code.

Upvotes: 4

user2364795
user2364795

Reputation: 11

If no zero argument constructor of an object it will also create an object and it will not throw any exception, please find the below code snippets.

try {
    Class o = Class.forName("com.myCompany.MyClass");

    Constructor m = o.getConstructor(Integer.class,String.class);
    m.newInstance(new Integer(0),new String(""));

} catch (ClassNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (InstantiationException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (IllegalAccessException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (SecurityException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (NoSuchMethodException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (IllegalArgumentException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (InvocationTargetException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

Upvotes: -1

salexander
salexander

Reputation: 954

While both effectively do the same thing, you should use the new operator instead of doing Class.forName('class').getInstance(). The latter uses the reflection API to lookup the class at runtime. By using the new operator, the VM will know beforehand that you want to use that class and thus be more efficient.

Upvotes: 0

stacker
stacker

Reputation: 68992

Class.forName can only call the default constructor (with no parameters) and class name can be provided during runtime e.g. the db-driver name read from a configuration file.

Upvotes: 5

Related Questions