dynamic instanciation of a generic class  
Author Message
Arnaud





PostPosted: 2005-2-15 4:10:00 Top

java-programmer, dynamic instanciation of a generic class Hi,

I've a question about Tiger (Java 5), genercity and dynamic instanciation
of class.

I can't found tutorial or sample via the Net.

By exemple :

public class A<T>
{
private T v;

public A(T v)
{
this.v=v;
}

public void test()
{
System.out.println(v.getClass().getName());
}
}


I'd like instanciate the A class with something like that : Class.forName
("A").... but why can I specified T parameter ?

Please, send me some sample or URL.

Thanks,
Arnaud.
 
John McGrath





PostPosted: 2005-2-15 6:41:00 Top

java-programmer >> dynamic instanciation of a generic class On 2/14/2005 at 3:10:08 PM, Arnaud wrote:

> I'd like instanciate the A class with something like that : Class.forName
> ("A").... but why can I specified T parameter ?

Java Generics work using "type erasure". Basically, that means that the
compiler knows about the type parameter, but it is then erased and the
type parameter is not used at runtime.

In other words, if you code:

List<String> list = new ArrayList<T>();

then the runtime type of the object created is "java.util.ArrayList", not
"java.util.ArrayList<T>".

Also note that the following will compile without errors, however, if you
have the "unchecked generics" warning turned on, it will get a warning on
the third line.

List<Integer> intList = new ArrayList<Integer>();
List<Float> floatList = new ArrayList<Float>();
intList = (List) floatList;
intList.add( 1 );
float f = floatList.get( 0 );

This will get ClassCastException on the last line, even though the code
does not contain an explicit cast -- the compiler automatically inserts
the cast (and the auto-unbox as well). If you compile this, and then
decompile it using JAD, you will get the following for the last line:

float f = ((Float)floatList.get(0)).floatValue();

--
Regards,

John McGrath