Java Generation Method Signature Explanation

What does this generic method signature mean?

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

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

I can not just write

 public D map(S sourceObject, java.lang.Class<D> destinationClass); 
+6
source share
3 answers

This means that this method call accepts two type parameters: S and D.

The <S, D> is understood as declaring that this method is general and accepts two type parameters, which are then used as placeholders for the actual types in the method signature.

When you call a method, you provide parameters or you get output from the types of expressions that you pass as arguments, for example:

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

In this case, S is Integer , and D is String

+8
source

I think that after the correction there is still an error (or you should show us the whole class if it also contains type parameters), but, I think, I understood your question; as already mentioned in the comments, you can simply get rid of a parameter of type S , because it is only used once in the method signature and replaces it with Object . A shortened version will look like this:

 public <D> D map(Object sourceObject, java.lang.Class<D> destinationClass); 
+2
source

<S, D> means that the method is generic (regardless of class). Get parameters of type S and class D ( Class<D> ). And return a value of type D - regardless of other types.

0
source

All Articles