[英]Java generics method signature explanation
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>
. 我指的是
<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);
That means that this method invocation takes two type parameters: S and D. 这意味着此方法调用需要两个类型参数:S和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. <S, D>
部分是指这种方法是通用的声明,它采用两个类型参数,然后用作方法签名中实际类型的占位符。
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
在这种情况下,S是
Integer
,D是String
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
. 正如在注释中已经说明的那样,你可以简单地去掉
S
类型参数,因为它只在方法签名中使用一次并用Object
替换它。 The reduced variant would then look like: 减少的变体将如下所示:
public <D> D map(Object sourceObject, java.lang.Class<D> destinationClass);
<S, D>
means that the method is generic (independent of class). <S, D>
表示该方法是通用的(独立于类)。 Get parameters of type S
and the class of D
( Class<D>
). 获取类型
S
参数和D
Class<D>
( Class<D>
)。 And return the value of type D
- independent of other types. 并返回
D
类型的值 - 独立于其他类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.