new
keyword or we use some DI framework e.g. Spring to create an object which internally use Java Reflection API to do so. In this Article, we are going to study the reflective ways to create objects.There are two methods present in Reflection API which we can use to create objects
- Class.newInstance() → Inside java.lang package
- Constructor.newInstance() → Inside java.lang.reflect package
Both
Class.newInstance()
and java.lang.reflect.Constructor.newInstance()
are known as reflective methods because these two uses reflection API to create the object. Both are not static and we can call earlier one on a class level object while latter one needs constructor level object which we can get by using the class level object.Class.newInstance()
TheClass
class is the most popular class in Java after the Object class. However, this class lies in the java.lang package but plays a major role in Reflection API (java.lang.reflect.*
package).In order to use
Class.newInstance()
we first need to get the class level instance of that class for which we want to create objects. We can do this by two ways one is writing complete name of the class and appending .class
to it and another is using Class.forName()
method, So in below code Employee.class
is similar to (Employee) Class.forName("org.programming.mitra.exercises.Employee")
Below code demonstrates how we can create objects using
Class.newInstance()
Employee emp = Employee.class.newInstance();
Or
Employee emp = (Employee) Class.forName("org.programming.mitra.exercises.Employee").newInstance();
Class.newInstance()
internally itself use the Constructor.newInstance()
to create the object as we can see in the source code of Class class, notice line no 430 and 442 in below image.Constructor.newInstance()
In order to useConstructor.newInstance()
method we first need to get constructor object for that class and then we can call newInstance()
on it to create objects as shown belowConstructor<Employee> constructor = Employee.class.getConstructor();
Employee emp3 = constructor.newInstance();
It internally use
sun.reflect.ConstructorAccessor
class to get the object, which is Oracle's private API.Difference between Class.newInstance() and Constructor.newInstance()
By name, both methods look same but there are differences between them which we are as following1. Class.newInstance() can only invoke the no-arg constructor,
Constructor.newInstance() can invoke any constructor, regardless of the number of parameters.
2. Class.newInstance() requires that the constructor should be visible,
Constructor.newInstance() can also invoke private constructors under certain circumstances.
3. Class.newInstance() throws any exception (checked or unchecked) thrown by the constructor,
Constructor.newInstance() always wraps the thrown exception with an InvocationTargetException.
Due to above reasons
Constructor.newInstance()
is preferred over Class.newInstance()
, that’s why used by various frameworks and APIs like Spring, Guava, Zookeeper, Jackson, Servlet etc.You can find complete code on this Github Repository and please feel free to provide your valuable feedback.
excellent material
ReplyDeleteThanks @Kiran
Delete"Constructor.newInstance() can also invoke private constructors under certain circumstances" what kind of circumstances?
ReplyDeleteThis code will do the trick, it will change the access modifier of the constructor to public
Deletetry {
Constructor constructor = Singleton.class.getDeclaredConstructor();
constructor.setAccessible(true);
singleton = constructor.newInstance();
// Constructor constructor = (Constructor) Class.forName("com.example.bloder.deck.SingletonActivity").getConstructor();
// singleton = constructor.newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
exactly..
DeleteAnkara
ReplyDeleteAntalya
istanbul
Ordu
izmir
LPNB
elazığ
ReplyDeletegümüşhane
kilis
siirt
sakarya
İWLEPM
amasya evden eve nakliyat
ReplyDeleteeskişehir evden eve nakliyat
ardahan evden eve nakliyat
manisa evden eve nakliyat
karaman evden eve nakliyat
36UW
64F74
ReplyDeleteÜnye Asma Tavan
Etimesgut Boya Ustası
Muğla Lojistik
Hakkari Evden Eve Nakliyat
Amasya Şehir İçi Nakliyat
Gate io Güvenilir mi
Konya Şehirler Arası Nakliyat
Antep Evden Eve Nakliyat
Erzincan Evden Eve Nakliyat
F47AA
ReplyDeletebinance indirim kodu %20
43029
ReplyDeleteerzincan tamamen ücretsiz sohbet siteleri
maraş chat sohbet
bartın rastgele canlı sohbet
sivas sesli sohbet uygulamaları
balıkesir mobil sesli sohbet
ığdır telefonda kızlarla sohbet
canlı sohbet bedava
malatya görüntülü sohbet canlı
elazığ görüntülü sohbet siteleri ücretsiz
560B3
ReplyDeleteelazığ mobil sohbet siteleri
sakarya sesli sohbet siteleri
muğla kadınlarla rastgele sohbet
burdur muhabbet sohbet
denizli canlı sohbet
mobil sohbet odaları
Şırnak Canlı Görüntülü Sohbet Odaları
kayseri bedava sohbet siteleri
sesli sohbet odası
10E10
ReplyDeletecanlı sohbet odaları
aydın sesli sohbet sesli chat
Kastamonu Canlı Sohbet Odaları
mersin telefonda kızlarla sohbet
Eskişehir Canlı Sohbet Ücretsiz
mobil sohbet et
rastgele sohbet
en iyi görüntülü sohbet uygulamaları
rastgele sohbet
468F6
ReplyDeleteAnc Coin Hangi Borsada
Trovo Takipçi Satın Al
Binance Kimin
Omlira Coin Hangi Borsada
Btcturk Borsası Güvenilir mi
Okex Borsası Güvenilir mi
Soundcloud Dinlenme Satın Al
Instagram Beğeni Hilesi
Binance Referans Kodu
35FCA
ReplyDeletekraken
probit
toptan sabun
canli sohbet
bingx
4g proxy
bybit
kraken
okex
F1825
ReplyDeleteücretli güvenilir show
BE5FA
ReplyDeletesanal ücretli show
E5FBB
ReplyDeleteücretli show