-4

What is the difference between Class.forName("Something"); and Class.forName("Something").newInstance(); Please clarify me.

Cœur
  • 34,719
  • 24
  • 185
  • 251
subash
  • 3,101
  • 2
  • 16
  • 22
  • The difference lies in the invocation of `newInstance()` obviously. So why don’t you look at the documentation of that method for finding out what it does? – Holger Nov 07 '13 at 08:40

3 Answers3

10
Class.forName("Somthing"); 

just loads the class in memory

Class.forName("Somthing").newInstance();

loads the class in memory and creates an instance of the class represented by the loaded Class.

Juned Ahsan
  • 66,028
  • 11
  • 91
  • 129
2

1 : if you are interested only in the static block of the class , the loading the class only would do , and would execute static blocks then all you need is

Class.forName("Somthing");

2 : if you are interested in loading the class , execute its static bloacks and also want to access its its non static part , then you need an instance and then you need

Class.forName("Somthing").newInstance();
0

Class.forName simply loads the class and the newInstance method invokes a new object

Class myclass = Class.forName("someClass"); // Load the class
someClass obj = (someClass) myclass.newInstance(); // someClass obj = new someClass()
Ankit Rustagi
  • 5,391
  • 11
  • 37
  • 68