Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java generics question with wildcards

Just came across a place where I'd like to use generics and I'm not sure how to make it work the way I want.

I have a method in my data layer that does a query and returns a list of objects. Here's the signature.

public List getList(Class cls, Map query)

This is what I'd like the calling code to look like.

List<Whatever> list = getList(WhateverImpl.class, query);

I'd like to make it so that I don't have to cast this to a List<Whatever> coming out, which leads me to this.

public <T> List<T> getList(Class<T> cls, Map query)

But now I have the problem that what I get out is always the concrete List<WhateverImpl> passed in whereas I'd like it to be the Whatever interface. I tried to use the super keyword but couldn't figure it out. Any generics gurus out there know how this can be done?

like image 876
Sean Avatar asked Jun 09 '10 16:06

Sean


People also ask

What are wildcards in generics in Java?

The question mark (?) is known as the wildcard in generic programming. It represents an unknown type. The wildcard can be used in a variety of situations such as the type of a parameter, field, or local variable; sometimes as a return type.

What are wildcards arguments in generics?

In generic code, the question mark (?), called the wildcard, represents an unknown type. The wildcard can be used in a variety of situations: as the type of a parameter, field, or local variable; sometimes as a return type (though it is better programming practice to be more specific).

Why do we need wildcard in generics in Java?

We can use the Java Wildcard as a local variable, parameter, field or as a return type. But, when the generic class is instantiated or when a generic method is called, we can't use wildcards. The wildcard is useful to remove the incompatibility between different instantiations of a generic type.

Can generics take multiple type parameters?

A Generic class can have muliple type parameters.


1 Answers

You need to define the method like this:

public <B, C extends B> List<B> getList(final Class<C> cls, final Map<?, ?> query)
like image 161
Joachim Sauer Avatar answered Oct 01 '22 05:10

Joachim Sauer