Take the 2-minute tour ×

Is it possible to declare the type of a generic using a class object?

For instance, I would like to do something like this:

Class returnType = theMethod.getReturnType();

AttributeComponent<returnType> attComponent;

attComponent = new AttributeComponent<returnType>(returnType, attName);
attributeComponents.put(methodName.substring(3), attComponent);

Now I know obviously this is incorrect, but is there a way to achieve this?

EDIT: explaining a little bit

I'm using reflection to go through all getters and then generate a UI element for each property (the AttributeComponent class, which has a JComponent element and a JLabel). I would like to use generics in order to create a getValue() method that would return an object of the property type.

share|improve this question
You can not do that. As returnType is variable and variables can not be used as Generic Parameters. –  Vash Oct 8 '12 at 8:51
add comment

2 Answers

I do not know if there is a way to compile something like that, but it has little value.

Think that thanks to type erasure, the compiled classes do not use the Generics information. That is, doing a Set<String> a = new Set<String>(); is useful for checking the use of a at compile time, but not at runtime.

So, you want to instantiate a Generic whose type will be only known at runtime, but at runtime it will not be used.

share|improve this answer
add comment

I would say this can be achieved by defining the method return type as generic; but you need to pass the actual type as a class argument to use it like you've shown:

<T> T yourMethod(Class<T> returnType) {
    // use <T> as generic and returnType to refer to the actual T class
    /* ... */ new AttributeComponent<T>(returnType, attName);

It would be also useful to see the larger context for what you're trying to do. If you want AttributeComponent.getValue() to return some generic type T (which is the method return type), that's completely useless unless you know each method return type at compile time, otherwise T will be nothing more than an Object. In my example above, you call yourMethod with a class that you already know and the same type will be returned (or some AttributeComponent of that type or whatever).

share|improve this answer
How does that solve my problem? I am trying to define the AttributeComponent generic type at run-time, if that is even possible (which @Vash already stated it isnt). I edited the original post for further info on what I'm trying to achieve) –  kelmer Oct 8 '12 at 9:10
Long story short, you can not use a class reference as a generic type. If you need both the class ref and the generic in a particular context, you need to pass them both to that method as in my example or you need to do it unsafely (keep the generic and cast the return type obtained via reflection to Class<T>). –  Costi Ciudatu Oct 8 '12 at 9:47
add comment

Your Answer


