Dave Richardson
Dave Richardson

Reputation: 5005

How to get a class instance of Parameterized type with two generics

I have:

public class RestClientResource<T,U> {
}

and want to determine the class of U.

I have this:

Class<U> uClass = 
(Class<U>) ((ParameterizedType)getClass().getGenericSuperclass()).getActualTypeArguments()[0];

but it doesnt't work, presumably because I have multiple generic parameterized types

How can I get this to work?

Upvotes: 0

Views: 71

Answers (1)

Andy Turner
Andy Turner

Reputation: 140318

but it doesnt't work, presumably because I have multiple generic parameterized type

This shouldn't be an issue.

There are a couple of things that jump out:

  1. You need there to actually be a generic superclass:

    getClass().getGenericSuperclass()
    

    Make your class abstract, in order that it has to be subclassed:

    public abstract class RestClientResource<T,U> {
    
  2. If you want the U class, access the [1]th element of the array:

    ....getActualTypeArguments()[1]
    

    Otherwise you get the T.

Upvotes: 2

Related Questions