如何将 class 范围的类型参数限制为原始包装器(数字)和字符串?

How to restrict class-scoped type parameter to primitive wrappers (numbers) and String?

如何将通用 class 中的 限制为基本包装类型(整数、长整型等)或字符串?像这样(伪代码):

public class GroupNotificationService<String OR T extends Number>

这可能吗?谢谢

你不能用类型参数做到这一点;如果它们确实允许有多个边界(如 T extends A & B 等),它们只是相加的。

但是您可以使用静态工厂方法来生成您的 class:

public static <T> GroupNotificationService<T> forClass(final Class<T> c)
{
    // check that c is correct, then
    return new GroupNotificationService<T>(whatever);
}