基于内部类中的类型参数的类型声明 [英] Type declaration based on type parameters in inner classes
问题描述
Java阴影类型参数吗?我发现很难自我测试,因为Java泛型无法在运行时得到验证.
Does Java shadow type parameters? I am finding it hard to test for myself because Java generics do not get reified at run time.
例如,给出以下代码:
public class NestedGeneric<T> {
private InnerGeneric<T> innerGenericInstance;
private static class InnerGeneric<T> {
public T innerGenericField;
}
NestedGeneric() {
innerGenericInstance = new InnerGeneric<T>();
}
}
下面的语句都可以很好地编译:
Both the below statements compile fine:
NestedGeneric<Integer> test1 = new NestedGeneric<Integer>();
NestedGeneric.InnerGeneric<String> test2 = new NestedGeneric.InnerGeneric<String>();
当将 NestedGeneric
传递给类型参数并调用其构造函数时, T
是什么?它总是与传递给 nestedGeneric
的type参数相同吗?
When the NestedGeneric
is passed a type parameter and its constructor called, what is T
? Is it always going to be the same as the type parameter passed to nestedGeneric
?
换句话说,可以将外部类的类型参数传递给内部类的泛型类型声明吗?
In other words, can an outer classes type parameters be passed to an inner classes generic type declarations?
推荐答案
换句话说,我想问题是,外部类可以输入吗参数传递给内部类的泛型类型声明?
In other words, I suppose the question is, can an outer classes type parameters be passed to an inner classes generic type declarations?
不.内部和外部 static 类之间没有任何关系(如继承或作为字段).您可以创建内部静态类的对象,而无需像在您的示例中那样对外部类进行任何依赖:
No. There is no relationship (like inheritance or as a field) between the outer and the inner static class. You can create an object of the inner static class without any dependency on the outer class like in your example:
NestedGeneric.InnerGeneric<String> test2 = new NestedGeneric.InnerGeneric<String>();
但是,当您使用内部类的实例作为字段时,泛型类型是从外部类派生的:
However when you use an instance of the inner class as a field the generic type is derived from the outer class:
private InnerGeneric<T> innerGenericInstance;
innerGenericInstance = new InnerGeneric<T>();
第三个变体是将内部类定义为字段(非静态):
private class InnerGeneric<T> {
public T innerGenericField;
}
由于它是成员变量,因此现在将从外部类获取类型.
which will now get the type from the outer class since its a member variable.
如注释中所指出的,它同时定义了内部静态&具有该类型的外部类只会使读者(以及您自己在稍后的时间)感到困惑.应该使用不同的泛型来声明它,例如
As pointed out in the comment defining both inner static & outer class with the type will just confuse the reader (and yourself at a later point in time). It should be declared with a different generic like
public class NestedGeneric<T> {
private InnerGeneric<T> innerGenericInstance;
private static class InnerGeneric<U> {
private U innerGenericField;
}
NestedGeneric() {
innerGenericInstance = new InnerGeneric<T>();
}
}
这篇关于基于内部类中的类型参数的类型声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!