Java泛型 - Java是否需要支持本地定义的类型? [英] Java generics - Does Java need support for locally defined types?
问题描述
我希望能在这里与Java仿制药专家联系。假设你有一些类型的类:
I am hoping to reach the Java generics experts here. Let's say you have some typed class:
public interface SomeClass<T> {
void doSomething(final T t);
}
还有一个函数可以获得 T
给定一个的实例SomeClass< T>
:
There is also a function which gets you an instance of T
given an instance of SomeClass<T>
:
public static class Retriever {
public <T> T get(final SomeClass<T> c) {
return null; // actual implementation left out
}
}
现在让我们说你有一个 SomeClass<?>
和一个检索器的集合:
Now let's say you have a collection of SomeClass<?>
and a retriever:
final List<SomeClass<?>> myClasses = null; // actual implementation left out
final Retriever myRetriever = null; // actual implementation left out
我们无法执行以下操作:
We are not able to do the following:
for (final SomeClass<?> myClass : myClasses) {
myClass.doSomething(myRetriever.get(myClass));
}
现在我的问题:Java是否需要支持才能在本地定义类型?类似于:
Now my question: does Java need support to be able to locally define a type? Something like:
<T> for (final SomeClass<T> myClass : myClasses) {
myClass.doSomething(myRetriever.get(myClass));
}
此处,类型 T
作用于for循环。我们定义 T
来摆脱通配符?
。而已。引入 T
应该使我们能够编写如上所述的所需for循环。
Here, the type T
is scoped to the for-loop. We are defining T
to get rid of the wildcard ?
. That's it. The introduction of T
should enable us to write the desired for loop as expressed above.
FWIW,以下代码是一种解决方法。我们正在推出一个功能,仅用于将?
转换为 T
。
FWIW, the following code is a workaround. We are introducing a function, solely for the conversion of ?
to T
.
for (final SomeClass<?> myClass : myClasses) {
workAround(myRetriever, myClass);
}
public static <T> void workAround(final Retriever myRetriever, final SomeClass<T> myClass) {
myClass.doSomething(myRetriever.get(myClass));
}
本地定义的用户类型可能是更优雅的解决方案吗?
A locally defined user type might be a more elegant solution?
推荐答案
现在我的问题:Java是否需要支持才能在本地定义类型?
Now my question: does Java need support to be able to locally define a type?
不。类型参数的最小范围是方法,即为了使for循环可以使用类型 T
,您必须将封闭方法定义为通用或封闭的类。例如:
No. The minimal scope of a type-parameter is the method, i.e. in order to have the type T
available for your for loop, you will have to either defined the enclosing method a generic or the enclosing class. For example:
<T> void method(List<SomeClass<T> myClasses) {
for (final SomeClass<T> myClass : myClasses) {
myClass.doSomething(myRetriever.get(myClass));
}
}
这篇关于Java泛型 - Java是否需要支持本地定义的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!