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

Obtaining the class of a generic type

XMLWordPrintable

    • Icon: Enhancement Enhancement
    • Resolution: Duplicate
    • Icon: P4 P4
    • None
    • 6
    • core-libs

      A DESCRIPTION OF THE REQUEST :
      You cannot obtain the class of a generic type such as "Class<LinkedList<String>>", e.g. for the purpose of creating a factory for generating an instance of the generic type. The following hypothetical class illustrates the problem.

      public class Factory<T> {
          private Class<T> factoryClass;
          public Factory(Class<T> factoryClass) {
              this.factoryClass = factoryClass;
          }
          public T createInstance() {
              try {
                  return factoryClass.getConstructor().newInstance();
              } catch (Exception e) {
                  return null;
              }
          }
      }

      This factory works for generating, e.g. "Object":

          new Factory<Object>(Object.class);

      However, it will not compile (without warnings) if I want to generate e.g. "LinkedList<String>" with this factory. I would like something like the following code to work:

          new Factory<LinkedList<String>>(LinkedList<String>.class);

      ,meaning that the statement "LinkedList<String>.class" should yield an object of type "Class<LinkedList<String>>". Other ways to obtainin an object of type "Class<LinkedList<String>>" would also solve the problem.


      JUSTIFICATION :
        To make clean code without warnings, it is sometimes necessary to be able to obtain Class<T> objects where T is a generic type, such as "LinkedList<String>". Without this enhancement, the language discriminates between non-generic types and generic types.

      A solution such as the one indicated would also allow a workaround for bug ID 5016825, without the need to introduce "C++ template-like" dynamic code generation (as I suspect solving this bug would require).


      EXPECTED VERSUS ACTUAL BEHAVIOR :
      EXPECTED -
      It should compile
      ACTUAL -
      Does not compile

      CUSTOMER SUBMITTED WORKAROUND :
      The following code will compile, but not without warning about using a "raw" type, and further warnings on type safety when the object produced by the factory is cast to a LinkedList<String>:

      f = new Factory<LinkedList>(LinkedList.class);
      LinkedList<String> a = (LinkedList<String>)f.createInstance();

            darcy Joe Darcy
            gmanwanisunw Girish Manwani (Inactive)
            Votes:
            0 Vote for this issue
            Watchers:
            0 Start watching this issue

              Created:
              Updated:
              Resolved:
              Imported:
              Indexed: