我想创建一个基本上像这样的类:
public class MyClass<T implements Serializable) {
void function() {
Class c = T.class;
}
}
两个错误:
- 我不能调用 T.class,即使我可以用任何其他对象类型调用它
- 我不能强制 T 以这种方式实现 Serializable
如何解决我的两个泛型问题?
干杯
尼克
最佳答案
你无法获取类型。
泛型是使用一种叫做 type-erasure 的东西实现的.
When a generic type is instantiated, the compiler translates those types by a technique called type erasure — a process where the compiler removes all information related to type parameters and type arguments within a class or method. Type erasure enables Java applications that use generics to maintain binary compatibility with Java libraries and applications that were created before generics.
其本质是类型信息被编译器使用并被丢弃,因此在运行时不可用。
关于执行 T implements Serializable
,您只需要以下内容:
public class MyClass<T extends Serializable>)
{
public void function(T obj)
{
...
}
}
这只是指是一个关系,所以一个实现了Serializable
的类,是一个 Serializable
并且可以传递给 function
。
关于java - 获取Java泛型的类,以及泛型的接口(interface)实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1320910/