Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is Class.newInstance() "evil"?

Ryan Delucchi asked here in comment #3 to Tom Hawtin's answer:

why is Class.newInstance() "evil"?

this in response to the code sample:

// Avoid Class.newInstance, for it is evil. Constructor<? extends Runnable> ctor = runClass.getConstructor(); Runnable doRun = ctor.newInstance(); 

so, why is it Evil?

like image 943
Amir Arad Avatar asked Oct 12 '08 10:10

Amir Arad


People also ask

What does class newInstance () do?

Class. newInstance() throws any exception thrown by the constructor, regardless of whether it is checked or unchecked. Constructor. newInstance() always wraps the thrown exception with an InvocationTargetException .

Why newInstance method was deprecated?

These calls can be replaced with a call to clazz. getDeclaredConstructor(). newInstance(). The reason for the deprecation is that that path bypasses compile-time exception checking.

What is newInstance in Java?

newInstance() creates a new instance of the class represented by this Class object. The class is instantiated as if by a new expression with an empty argument list. The class is initialized if it has not already been initialized. .

What is Java reflection?

Reflection is a feature in the Java programming language. It allows an executing Java program to examine or "introspect" upon itself, and manipulate internal properties of the program. For example, it's possible for a Java class to obtain the names of all its members and display them.


1 Answers

The Java API documentation explains why (http://java.sun.com/javase/6/docs/api/java/lang/Class.html#newInstance()):

Note that this method propagates any exception thrown by the nullary constructor, including a checked exception. Use of this method effectively bypasses the compile-time exception checking that would otherwise be performed by the compiler. The Constructor.newInstance method avoids this problem by wrapping any exception thrown by the constructor in a (checked) InvocationTargetException.

In other words, it can defeat the checked exceptions system.

like image 61
Chris Jester-Young Avatar answered Oct 19 '22 09:10

Chris Jester-Young