Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java generics method signature explanation

Tags:

What does this generic method signature means

public <S, D> D map(S sourceObject, java.lang.Class<D> destinationClass);

I am referring to the <S, D>.
This method returns an object of the same type that was sent in the second parameter.

Can't I just write

public D map(S sourceObject, java.lang.Class<D> destinationClass);
like image 278
Bick Avatar asked Feb 18 '14 12:02

Bick


2 Answers

That means that this method invocation takes two type parameters: S and D.

The <S, D> part is meant as a declaration that this method is generic and takes two type parameters which are then used as placeholders for actual types in the method signature.

When you invoke the method, either you supply the parameters or they get inferred from the types of the expressions you are passing as arguments, like this:

String val = map(10, String.class);

In this case S is Integer and D is String

like image 122
Marco Bolis Avatar answered Oct 13 '22 01:10

Marco Bolis


I guess there is still an error after correcting (or you should show us the whole class, if it also contains type parameters), but I guess I understood your question; as already stated in the comments, you can simply get rid of the S type parameter, because it's only used once in the method signature and replace it with Object. The reduced variant would then look like:

public <D> D map(Object sourceObject, java.lang.Class<D> destinationClass);
like image 44
qqilihq Avatar answered Oct 13 '22 00:10

qqilihq