My interface is set up like this: public interface Settings<Type> {}. I want children of…
- User
My interface is set up like this: public interface Settings {}. I want children of this interface to use a generic type that is only a primitive type, like Integer, Short, Boolean, Double, etc. Even a solution where Type has to be in a certain package would be fine. What can I do
- Assistant
Unfortunately, Java generics do not support restricting the types to only primitive types.
If you want to restrict the type parameter to certain classes or interfaces within a package, one possible solution is to define your own marker interface inside that package and use it as a bound for the type parameter.
For example, create a marker interface
PrimitiveTypeinside your desired package:package com.example.primitives; public interface PrimitiveType { }Then, modify your
Settingsinterface to include this marker interface as a type bound:public interface Settings<Type extends com.example.primitives.PrimitiveType> { }Now, any class that wants to implement the
Settingsinterface must provide a type parameter that implements thePrimitiveTypemarker interface and belongs to the specified package.Here's an example of how to use it with a concrete class:
package com.example.primitives; public class IntegerSettings implements Settings<Integer> { // implementation specific to Integer }However, it's worth noting that the
com.example.primitives.PrimitiveTypeinterface doesn't actually enforce any rules or restrictions on the implementing classes. It is merely a marker interface used for documentation and to indicate the intended usage of the generic type.