Java通用字段声明 [英] Java generic field declaration
问题描述
在没有泛型类型的类中,我想声明一个类似于这些的相当复杂的泛型字段:
In a class without generic types I want to declare a rather complex generic field similar to these:
public class Client {
private Map<Class<T extends Serializable>, List<Consumer<S extends T>>> classToConsumerTry1;
private <T extends Serializable, S extends T> Map<Class<T>, List<Consumer<S>>> classToConsumerTry2;
}
promblem是java编译器不会让我:)
promblem is the java compiler won't let me :)
所以我的问题是如何正确引入T和S而不向我的班级客户添加类型。
So my question is how do I correctly introduce T and S without adding types to my class Client.
我的目标是强制执行 Class
作为 Serializable
的子类型和 Consumer
是您为 Class
选择的类的子类型。
My goal is to enforce the Class
being a subtype of Serializable
and the Consumer
being a subtype of the class you chose for Class
.
推荐答案
你不能。您唯一的选择是在 Client
类声明中声明泛型类型参数。如果 Client
类没有泛型类型参数,则其成员不能是通用的。您必须在班级成员的声明中使用实际类型。
You can't. Your only option is to declare the generic type parameters in your Client
class declaration. If your Client
class has no generic type parameters, its members can't be generic. You must use actual types in the declaration of your class members.
这篇关于Java通用字段声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!