devxlogo

Avoid Poor Use of Reflection

Avoid Poor Use of Reflection

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)) ???
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist