Restrict Java generic parameter types to a list of final classes

T is not limited in the following statement

abstract public class Defaults<T>

However, my defaults class only handles string, integer and double Therefore, I want to limit t to string, double

Obviously, the following are not allowed because they are Finals:

abstract public class Defaults<T extends String&Integer&Double>

How can I do that?

Solution

You can't The closest thing you can do is give defaults a private constructor

private Defaults() {}

... and provide factory methods only for allowed classes:

public static Defaults<String> stringDefaults() { return new Defaults<>(); }
public static Defaults<Integer> integerDefaults() { return new Defaults<>(); }
public static Defaults<Double> doubleDefaults() { return new Defaults<>(); }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>