Amit Yadav
Amit Yadav

Reputation: 35044

Java Generic Type syntax

<D extends com.j256.ormlite.dao.Dao<T,?>,T> D getDao(Class<T> clazz)

I am not able to understand above statement

getDao(Class clazz) returns D

D having following constraints

D extends com.j256.ormlite.dao.Dao<T,?>

and extra ,T i am not able to understand.

Could you please explain it ?

Upvotes: 1

Views: 99

Answers (2)

tobias_k
tobias_k

Reputation: 82899

This method has two type parameters, D and T, with D having an additional extends constraint, depending on T. Don't get confused by this <T,?>,T syntax; the ,T does not belong to the constraint, but is the second parameter, telling Java that T is not the name of a concrete class.

If you add a space or swap the parameters, it will be clearer. Here's a similar, but somewhat simpler example. These method signatures are all equivalent:

<D extends List<T>,T>   D createListOf(Class<T> clazz)  // your version
<D extends List<T>, T>  D createListOf(Class<T> clazz)  // extra space
<T, D extends List<T>>  D createListOf(Class<T> clazz)  // different order

Keep in mind that, even though it may seem apparent that T is another type parameter, this is not clear to Java. There could be an actual class named T, so we have to be explicit that T is a type parameter.

class T { ... } // this T is not what I want!

Conversely, type parameters are not restricted to single characters. You could also have a type parameter called Foo, or even String, if you want to utterly confuse your co-workers. Maybe that makes clear why the declaration of all type parameters using <...> is necessary.

// just a deterrent example; don't do this! String as parameter, not class
<String, Foo extends List<String>> Foo createListOf(Class<String> clazz)

Upvotes: 2

Mena
Mena

Reputation: 48404

This method will:

  • Return an object of type D
  • Where D is or extends com.j256.ormlite.dao.Dao, parametrized with an object of type T or extending/implementing T and an unknown type parameter
  • If given as argument a class of type T

It uses a lot of generic abstraction, which is not surprising given it delivers a DAO (Data Access Object).

Upvotes: 1

Related Questions