如何在java泛型中定义类型参数的静态字段 [英] how to define static fields for type parameter in java generics
问题描述
我想定义一个如下的时间接口:
public interface TimeInterface< T>
{
static T ZERO;
static T INFINITY;
//一些其他方法...
}
或者如何做到这一点,以避免错误?
在此先感谢! 解决方案
直接从 javadoc :
我们不能声明类型为类型参数的静态字段类的静态字段是一个类级变量,类的静态对象。因此,不允许使用类型参数的静态字段。考虑以下类:
public class MobileDevice< T> {
private static T os;
// ...
}
如果静态字段的类型参数是被允许的,那么下面的代码会被混淆:
MobileDevice< Smartphone> phone = new MobileDevice<>();
MobileDevice< pager> pager = new MobileDevice<>();
MobileDevice< TabletPC> pc = new MobileDevice<>();
由于静态字段os由电话,寻呼机和pc共享,所以实际类型操作系统?它不能同时是智能手机,传呼机和 TabletPC
。因此,您不能创建类型参数的静态字段。
I want to define a time interface like that:
public interface TimeInterface<T>
{
static T ZERO;
static T INFINITY;
// some other methods...
}
Is this possible, or how to do that to avoid errors?
Thanks in advance!
From the javadoc directly:
We cannot declare static fields whose types are type parameters
A class's static field is a class-level variable shared by all non-static objects of the class. Hence, static fields of type parameters are not allowed. Consider the following class:
public class MobileDevice<T> {
private static T os;
// ...
}
If static fields of type parameters were allowed, then the following code would be confused:
MobileDevice<Smartphone> phone = new MobileDevice<>();
MobileDevice<Pager> pager = new MobileDevice<>();
MobileDevice<TabletPC> pc = new MobileDevice<>();
Because the static field os is shared by phone, pager, and pc, what is the actual type of os? It cannot be Smartphone, Pager, and TabletPC
at the same time. You cannot, therefore, create static fields of type parameters.
这篇关于如何在java泛型中定义类型参数的静态字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!