IveCal <ive....@gmail.com> wrote:
class Gen<T>{
T ob;
Gen(){
ob = new T(); // <---- POINT OF CONFUSION
}
}
My question is: why is it illegal to instantiate ob = new T();?
http://java.sun.com/docs/books/tutorial/java/generics/erasure.html
T is a placeholder that ONLY exists to automatically cast things, and
to check that it's safe to do so. It inserts casts around the uses, but the
underlying type in the code is Object (or the supertype specified in something
like <T extends CharSequence>).
I thought T is replaced with the appropriate type (through the process
called erasure) during COMPILE time so that it will look AS IF IT WERE
WRITTEN like this:
// Assume argument type is String
class Gen{
java.lang.String ob;
Gen(){
ob = new java.lang.String(); // I assumed it look like this.
}
}
Let's also give it a method
T getObj() { return ob; }
The Gen class is one set of code, and it hast to work correctly with all the
following:
Gen<Object> obgGen = new Gen<Object>();
Object o = objGen.getObj();
Gen<String> strGen = new Gen<String>();
String s = strGen.getObj();
Gen<Integer> intGen = new Gen<Integer>();
Integer i = intGen.getObj();
To do so, it cannot keep a member with a specific type, or it would work with
one and not others. It keeps an Object, and casts it as necessary. Generic
use that can't be accomplished with a cast isn't allowed.
This means you can't new up things of a specific type, because that exact
non-type-specific code has to work with multiple type specifiers.
The common workarounds are to use a template or factory in the Gen class, that
is specified as an argument to the thing that needs to construct objects.
class Gen<T extends Clonable> {
private T ob;
public Gen(T templateObject) {
ob = templateObject.clone()
}
...
}
You can do similar stuff by reflecting on the templateObject, or by passing a
factory, as in:
public class Foo {
public interface Factory<U> {
public U getInstance();
}
public static class Gen<T> {
private T obj;
Gen(Factory<T> factory) {
obj = factory.getInstance();
}
T getObj() { return obj; };
}
public static void main(String[] args) {
Gen<String> stringGen = new Gen<String>(new Factory<String>() {
public String getInstance() { return "foofoo"; }
});
System.out.println(stringGen.getObj());
}}
--
Mark Rafn da...@dagon.net <http://www.dagon.net/>
Yup, I got your point. Thanks for the reply.