Peter Kelley
Peter Kelley

Reputation: 2360

How do I Invoke a Generic Method with Specific Type Parameters?

I have a method with the following signature:

<T> T getBody(Class<T> type)

that returns the body object as the specified type. How do I invoke it to return an object of type

Iterable<OProperty<?>>

I did a lot of Java before generics so my programmer fu is a little rusty in these circumstances :)

Upvotes: 2

Views: 97

Answers (2)

newacct
newacct

Reputation: 122439

Class and generics doesn't work together very well. Class is for representing concrete runtime types, while generics is at compile time. We would like to have Class<Iterable> and Class<Iterable<Something>>, etc., but at runtime there is only one such object. No type for it would fit all of these uses. Java chose Class<Iterable>.

You can use some dubious unchecked casts to get the right type to pass to it:

getBody(Class<Iterable<OProperty<?>>>)(Class<?>)Iterable.class)

Upvotes: 0

prunge
prunge

Reputation: 23248

This can't be done with Class<T>. The only allowed T is a raw type because that is all that Class can be parametrized with (you can have Class<List> but not Class<List<String>>).

Upvotes: 5

Related Questions