22

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);
5
  • 1
    What is the difference? Commented Feb 18, 2014 at 12:36
  • 3
    That's why copy-paste is dangerous. Commented Feb 18, 2014 at 12:37
  • 3
    Too much paste, not enough cut. Commented Feb 18, 2014 at 12:39
  • 1
    Let me guess, the second should read public <D> D map(Object sourceObject, java.lang.Class<D> destinationClass);. It's the same, type parameter S is not necessary. Commented Feb 18, 2014 at 12:39
  • 1
    Alright guys. Nothing to see here in the comments. edited the original question. and thanks. Commented Feb 18, 2014 at 13:10

3 Answers 3

19

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

Sign up to request clarification or add additional context in comments.

1 Comment

You need to explain more :(
4

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);

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.