JDK-6463234 : Obtaining the class of a generic type
  • Type: Enhancement
  • Component: core-libs
  • Sub-Component: java.lang:reflect
  • Affected Version: 6
  • Priority: P4
  • Status: Closed
  • Resolution: Duplicate
  • OS: linux
  • CPU: x86
  • Submitted: 2006-08-23
  • Updated: 2012-09-28
  • Resolved: 2006-08-23
Related Reports
Duplicate :  
Description
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();

Comments
EVALUATION The required information is not available at runtime; addressing this issue would require "reification" of type parameters. Closing as a duplicate of 5098163.
23-08-2006