What is the difference between Class.forName("Something"); and Class.forName("Something").newInstance(); Please clarify me.
Asked
Active
Viewed 327 times
-4
-
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 Answers
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
-
3
-
-
@subash to initialize some resource at the class loading time i.e inside static blocks of a class. – Juned Ahsan Nov 07 '13 at 06:43
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();
Hussain Akhtar Wahid 'Ghouri'
- 6,407
- 8
- 49
- 83
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