Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / November 2007

Tip: Looking for answers? Try searching our database.

Confused with Generics

Thread view: 
IveCal - 19 Nov 2007 17:24 GMT
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
Lew - 19 Nov 2007 17:38 GMT
> I cant understand this piece of code regarding generics.
>
[quoted text clipped - 9 lines]
> 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:
>
[quoted text clipped - 6 lines]
>  }
> }

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>

Signature

Lew

IveCal - 19 Nov 2007 20:07 GMT
> > I cant understand this piece of code regarding generics.
>
[quoted text clipped - 65 lines]
> --
> Lew

Hi Lew,

Thanks for the idea.

Regards,
Ive
Mark Rafn - 19 Nov 2007 19:05 GMT
>class Gen<T>{
> T ob;
[quoted text clipped - 3 lines]
> }
>}

>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{
[quoted text clipped - 4 lines]
> }
>}

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    dagon@dagon.net    <http://www.dagon.net/>
IveCal - 19 Nov 2007 20:01 GMT
> >class Gen<T>{
> > T ob;
[quoted text clipped - 85 lines]
> --
> Mark Rafn    da...@dagon.net    <http://www.dagon.net/>

Hi Rafin,

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

Best regards,
Ive


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2009 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.