Confused with Generics

I

IveCal

Hi all,

Please help. I cant understand this piece of code regarding generics.
See the code below:

class Gen<T>{
T ob;

Gen(){
ob = new T(); // <---- POINT OF CONFUSION
}
}

My question is: why is it illegal to instantiate ob = new T();?
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.
}
}




Please help! I'm stuck!



Regards,
Ive
 
L

Lew

IveCal said:
I cant understand this piece of code regarding generics.

class Gen<T>{
T ob;

Gen(){
ob = new T(); // <---- POINT OF CONFUSION
}
}

why is it illegal to instantiate ob = new T();?
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

How would the compiler know that String is involved? That would only be known
at run time.
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.
}
}

In this case, all the type-resolution mechanism can tell is that T is some
Object type. T might not have a no-arg constructor, so the compiler cannot
tell that 'new T()' is a valid constructor. You can pass in a Class <?
extends T> object to provide run-time type information (RTTI):

<example>
package testit;

import java.util.logging.Level;
import java.util.logging.Logger;

public class General <T>
{
private final Class <? extends T> clazz;
private final T ob;

public General( Class<? extends T> clazz )
{
try
{
ob = clazz.newInstance();
}
catch ( InstantiationException ex )
{
Logger.getLogger( getClass().getName() )
.log( Level.SEVERE, null, ex );
throw new RuntimeException( "Illegal constructor", ex );
}
catch ( IllegalAccessException ex )
{
Logger.getLogger( getClass().getName() )
.log( Level.SEVERE, null, ex );
throw new RuntimeException( ex );
}
this.clazz = clazz;
}
}
</example>
 
M

Mark Rafn

IveCal said:
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 said:
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());
}
}
 
I

IveCal

IveCal said:
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 said:
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());
}}

Hi Rafin,

Yup, I got your point. Thanks for the reply.

Best regards,
Ive
 
I

IveCal

How would the compiler know that String is involved? That would only be known
at run time.




In this case, all the type-resolution mechanism can tell is that T is some
Object type. T might not have a no-arg constructor, so the compiler cannot
tell that 'new T()' is a valid constructor. You can pass in a Class <?
extends T> object to provide run-time type information (RTTI):

<example>
package testit;

import java.util.logging.Level;
import java.util.logging.Logger;

public class General <T>
{
private final Class <? extends T> clazz;
private final T ob;

public General( Class<? extends T> clazz )
{
try
{
ob = clazz.newInstance();
}
catch ( InstantiationException ex )
{
Logger.getLogger( getClass().getName() )
.log( Level.SEVERE, null, ex );
throw new RuntimeException( "Illegal constructor", ex );
}
catch ( IllegalAccessException ex )
{
Logger.getLogger( getClass().getName() )
.log( Level.SEVERE, null, ex );
throw new RuntimeException( ex );
}
this.clazz = clazz;
}}

</example>

Hi Lew,

Thanks for the idea.

Regards,
Ive
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

generics puzzle 57
Generics 12
can this be done with generics? 32
Creating arrays using GENERICS 4
Confusion with templates, generics, and instanceof 17
Generics Issue 13
Generics and reflection 2
Generics and for each 12

Members online

Forum statistics

Threads
474,432
Messages
2,571,680
Members
48,796
Latest member
Greg L.

Latest Threads

Top