Re: Generics: instantiating an object from a class name in configuration
markspace <nospam@nowhere.com> wrote:
Lew wrote:
try
{
// ClassCastException caught so this is safe
@SuppressWarnings( "unchecked" )
Class <Authenticator> clazz =
(Class <Authenticator>) Class.forName( name );
authenticator = clazz.newInstance();
}
The following doesn't generate any warning messages and doesn't require
a @SuppressWarnings annotation. It's also a tad shorter. It will throw
ClassCastException if the type loaded isn't right, but that could be
caught too. I'm not sure it's better, but it is an alternative.
try
{
Class<?> c = Class.forName( "test" );
SomeType s = (SomeType) c.newInstance();
Do never use Class.newInstance(), it will pass through /any/ Throwable
that the actual code throws (it is actually one way to throw a checked exception
that is not declared). Instead use the explicit no-argument Constructor.
Strictly speaking, if a reflectively invoked method throws InterruptedException
(wrapped in the InvocationTargetException), one should also interrupt the current
Thread (or pass the InterruptedException on), as otherwise the interruption is
swallowed.