M Rajoy
M Rajoy

Reputation: 4114

Define a generic type with a class object at runtime

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.

Upvotes: 0

Views: 210

Answers (2)

Costi Ciudatu
Costi Ciudatu

Reputation: 38265

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).

Upvotes: 2

SJuan76
SJuan76

Reputation: 24895

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.

Upvotes: 3

Related Questions