I have a situation where I am creating a data model class that has all the data points needed for a specific class. However depending on what is called in the class it does not need all the variables. The data model has multiple bounded type parameters however if not all are being used can some of them be optional?
For example:
public class DataModel<OBJ extends Object, EXCEPT extends Exception, MODEL extends BaseModelClass> {
}
Then when I instantiate it I might not need model and want to do something like:
DataModel<ClassA,RunTimeException,null> data = new DataModel<ClassA,RunTimeException,null>();
Where ClassA is a defined class that extends object in another part of the code and BaseModel is a company base model that has some very common pieces.
So the question is can something like this be done and have some of the bounded type parameters that apply to fields not being used for a specific submethod in this class be optional?
答案 0 :(得分:1)
在声明泛型变量时,不能仅指定泛型类的某些参数化类型:它将是编译错误。 根据定义的边界指定和有效的泛型类的所有参数化类型,或者应使用原始类型。
请注意,如果您不想定义更具体的类型,则可以声明与下限通配符相同的类型:
DataModel<ClassA,RunTimeException,BaseModelClass> data = new DataModel<>();
或者像(如Lexicore所提到的)通配符:
DataModel<ClassA,RunTimeException,?> data = new DataModel<>();
根据您的要求,我会补充说,泛型不是为了向类中添加/删除新方法而设计的。这些旨在更精确地键入类的实例。 此外,您更多地在客户端类使用的类中定义泛型,对客户端使用它可能很麻烦。