简体   繁体   中英

In Java Can I have Multiple Bounded Type Parameters But Be Optional

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?

You cannot specify only some of the parameterized types of the generic class as you declare a generic variable : it would be a compilation error. Either all parameterized types of the generic class are specified and valid according to the bounds defined or a raw type should be used.

Note that you could declare the same type as the lowerbound wildcard if you don't want to define a more specific type to:

DataModel<ClassA,RunTimeException,BaseModelClass> data = new DataModel<>();

Or a wildcard such as (as mentioned by Lexicore) :

DataModel<ClassA,RunTimeException,?> data = new DataModel<>();

According to your requirement, I would add that the generics are not designed to add/remove new methods to a class. These are designed to type more precisely instances of the class. Besides, more you define generics in a class used by client classes more it may be cumbersome to use for clients.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM