[英]Compiler change in Java 7
在Java 6中,我能够使用:
public static <T, UK extends T, US extends T> T getCountrySpecificComponent(UK uk, US us) {
Country country = CountryContext.getCountry();
if (country == Country.US) {
return us;
} else if (country == Country.UK) {
return uk;
} else {
throw new IllegalStateException("Unhandled country returned: "+country);
}
}
使用这些存储库:
public interface Repository{
List<User> findAll();
}
public interface RepositoryUS extends Repository{}
public interface RepositoryUK extends Repository{}
使用这些时:
RepositoryUK uk = ...
RepositoryUS us = ...
这行在Java6中编译但在Java7中失败(错误找不到符号 - 因为编译器在类Object上查找findAll())
List<User> users = getCountrySpecificComponent(uk, us).findAll();
这在Java 7中编译
List<User> users = ((Repository)getCountrySpecificComponent(uk, us)).findAll();
我知道这是一个相当罕见的用例,但有没有理由进行这种改变? 还是一种告诉编译器有点“更聪明”的方法?
我认为应该限制T
来扩展Repository
。 这样编译器就知道getCountrySpecificComponent
返回一些存储库。
编辑:
写的也应该没问题: public static <T extends Repository> T getCountrySpecificComponent(T uk, T us)
然后我同意旧编译器接受它是错误的。 我想你想要这样的东西:
public interface UserFindingComponent{
List<User> findAll();
}
public interface Repository extends UserFindingComponent{ }
public interface RepositoryUS extends Repository{}
public interface RepositoryUK extends Repository{}
...
public static <T extends UserFindingComponent, UK extends T, US extends T> T getCountrySpecificComponent(UK uk, US us) {
Country country = CountryContext.getCountry();
if (country == Country.US) {
return us;
} else if (country == Country.UK) {
return uk;
} else {
throw new IllegalStateException("Unhandled country returned: "+country);
}
}
在这种情况下,编译器无法推断类型参数,这也可能是Java 6中的情况。 您可以使用以下语法告诉编译器泛型类型是什么:
import java.util.List;
class User {
}
interface Repository {
List<User> findAll();
}
interface RepositoryUS extends Repository {
}
interface RepositoryUK extends Repository {
}
class Test {
public static <T, UK extends T, US extends T> T getCountrySpecificComponent(UK uk, US us) {
Country country = CountryContext.getCountry();
if (country == Country.US) {
return us;
} else if (country == Country.UK) {
return uk;
} else {
throw new IllegalStateException("Unhandled country returned: " + country);
}
return us;
}
public static void main(String... args) {
RepositoryUK uk = null;
RepositoryUS us = null;
List<User> users = Test.<Repository, RepositoryUK, RepositoryUS>getCountrySpecificComponent(uk, us).findAll();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.