Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-5016825

Allow creating a new instance of a generic type

XMLWordPrintable

    • Icon: Enhancement Enhancement
    • Resolution: Duplicate
    • Icon: P5 P5
    • None
    • 5.0
    • specification
    • x86
    • windows_xp

      Name: jl125535 Date: 03/19/2004


      A DESCRIPTION OF THE REQUEST :
      You cannot create a new instance of a generic type. Nor is there any way to obtain the Class of that generic. I would like to be able to perform the following function:

      class MyClass<T>
      {
          T enclosedInstance;

          public MyClass()
           {
               enclosedInstance = T.class.newInstance(); // like Object.class
           }
      }

      The usage code will allow me to create an instance without too much fuss like this:

      MyClass<DefaultMyInterface> system = new MyClass<DefaultMyInterface>();
      system.enclosedInstance.doSomething();


      JUSTIFICATION :
      When you have a parameterized interface that solves some problems, using that parameterized interface can be rather an inconvenience. For example, in my code I have an interface like this:

      interface Profile<VALIDATOR extends ComponentValidator,
                                     FACTORY extends ComponentFacotry,
                                     ASSEMBLER extends Assembler>
      {
          VALIDATOR getValidator();
          FACTORY getFactory();
          ASSEMBLER getAssembler();
      }

      When I have a definition class, it is very simple:

      class DefaultProfile impelments
           Profile<TypeManager,TypeManager,DefaultAssembler>
      {
          // ... the implementation
      }

      That way I can create a new container for my profile without having to do it in two steps. Right now I have to do this:

      DefaultProfile profile = new DefaultProfile();
      Container container = new Container(profile);

      profile.getAssembler().invokeMethodNotInInterface();

      The important thing is that I want to separate how the container uses the profile from the way the client uses it. I would like to simplify the useage to the following:

      Container<DefaultProfile> container = new Container<DefaultProfile>();
      container.getProfile().getAssembler().invokeMethodNotInInterface();

      Make it more compact.

      EXPECTED VERSUS ACTUAL BEHAVIOR :
      EXPECTED -
      T.class.newInstance() operates the same way that Object.class.newInstance() operates.
      ACTUAL -
      Compile error
      (Incident Review ID: 244080)
      ======================================================================

            abuckley Alex Buckley
            jleesunw Jon Lee (Inactive)
            Votes:
            0 Vote for this issue
            Watchers:
            0 Start watching this issue

              Created:
              Updated:
              Resolved:
              Imported:
              Indexed: