简体   繁体   English

Java泛型语法之间的区别?

[英]Difference between Java generics syntax?

What is the difference between these method definitions? 这些方法定义有什么区别?

public <T extends Foo> void loadData(Class<T> p_class);

public void loadData(Class<? extends Foo> p_class);

Both signatures accept exactly the same set of arguments, so in that sense are equivalent. 两个签名都接受完全相同的参数集,因此在这个意义上是等价的。 As pointed out in the comments, in the second case you will not be able to refer to T in the body of the method. 正如评论中指出的那样,在第二种情况下,您将无法在方法体中引用T However, according to Effective Java, the second signature is preferred (as it is shorter and slightly clearer). 但是,根据Effective Java,第二个签名是首选(因为它更短,更清晰)。 In that book, the advice given is to use the second signature, and use a private helper method with the first signature if T is required in the method. 在该书中,给出的建议是使用第二个签名,如果方法中需要T则使用带有第一个签名的私有帮助器方法。 Like this: 像这样:

private <T extends Foo> void helper(Class<T> p_class) {
    // code
}

public void loadData(Class<? extends Foo> p_class) {
    helper(p_class);
}

There is a difference in syntactic usage, as the second method has a generic type parameter. 语法用法存在差异,因为第二种方法具有泛型类型参数。

class Bar extends Foo { }

obj.<Bar>loadData(klazz);

This requires klazz to be Class<Bar> exactly. 这要求klazz完全是Class<Bar>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM