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?
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 .
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.
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. .
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With