dcsimg
 

Submitted by: Octavia Anghel(octaviaanghel@gmail.com)

Wednesday Aug 15th 2018 by Octavia Anghel

Language: Java, Expertise: Beginner - Learn more about why it is dangerous to create an instance of a class you don't know.

Class beanClass = ???
If (beanClass.newInstance() instanceof TestBean) ???

The above code is tries to use the reflection API, it tries to find a way to check for inheritance, but it didn't find a way to do it. So it just created a new instance and uses the instanceof operator. It is dangerous to create an instance of a class you don't know. You never know what this class does, it could be very costly or the default constructor may not even exist. The right way to do this check is to use the Class.isAssignableFrom(Class) method:

Class beanClass = ???
If (TestBean.class.isAssignableFrom(beanClass)) ???
Home
Mobile Site | Full Site