A
allen
Hi,
While generics ought to be saving me time, I'm spending far more time
trying to figure it out than I can afford!
Here we go. I want a factory method for creating new instances of a
known base class given the class name. Then I want to call that factory
method, expecting a parameterized instance in return.
basic factory method, ignoring exceptions:
public static <T> T create( Class<T> base, String classname ) throws
Exception
{
Class<? extends T> clazz = Class.forName( classname ).asSubclass(
base );
return clazz.newInstance( );
}
this works for simple objects:
java.awt.Component c = create( java.awt.Component.class,
"java.awt.Button" );
But now I want to create a parameterized instance:
List<String> list = create( List.class, "java.util.LinkedList" );
which gives me the unchecked cast warning. Obviously the String type is
not being handed in anywhere, but trying create( List<String>.class,
"ja...") doesn't compile.
How do I declare my factory method to handle both cases with no
warning? I'm trying to work out the "correct" way, so ideally I don't
want to @Suppress anything.
Thanks
Allen
While generics ought to be saving me time, I'm spending far more time
trying to figure it out than I can afford!
Here we go. I want a factory method for creating new instances of a
known base class given the class name. Then I want to call that factory
method, expecting a parameterized instance in return.
basic factory method, ignoring exceptions:
public static <T> T create( Class<T> base, String classname ) throws
Exception
{
Class<? extends T> clazz = Class.forName( classname ).asSubclass(
base );
return clazz.newInstance( );
}
this works for simple objects:
java.awt.Component c = create( java.awt.Component.class,
"java.awt.Button" );
But now I want to create a parameterized instance:
List<String> list = create( List.class, "java.util.LinkedList" );
which gives me the unchecked cast warning. Obviously the String type is
not being handed in anywhere, but trying create( List<String>.class,
"ja...") doesn't compile.
How do I declare my factory method to handle both cases with no
warning? I'm trying to work out the "correct" way, so ideally I don't
want to @Suppress anything.
Thanks
Allen