我正在尝试创建一个通用的Identifier
类,我可以按如下方式使用它:
public class TestGenericIdentifier {
public static void main(String[] args) {
Identifier<Car> carId = new Identifier<>(Car.IdentifierType.LICENSE_PLATE, "123 XYZ");
Identifier<Person> personId = new Identifier<>(Person.IdentifierType.SOCIAL_SECURITY, "123456");
System.out.println(carId);
System.out.println(personId);
}
}
为此,我开始创建一个Identifiable
界面:
public interface Identifiable<T extends Enum> {}
实现Identifiable
的类需要在其声明中提供枚举T
,这是Identifier
构造函数的第一个参数的类型:
public class Identifier<E extends Identifiable<T>> { //does not compile
public Identifier(T type, String value) {
//some code
}
}
现在上面的代码没有编译,因为我只能在第一行使用Identifiable
(无参数T
)。如果它工作,我将能够编写以下两个类:
public class Car implements Identifiable<Car.IdentifierType>{
public enum IdentifierType {
SERIAL_NUMBER,
LICENSE_PLATE;
}
}
public class Person implements Identifiable<Person.IdentifierType> {
public enum IdentifierType {
DATABASE_ID,
SOCIAL_SECURITY;
}
}
使用泛型有没有办法做到这一点?
编辑
一种方法是通过执行以下操作来降低简洁性并保持编译时类型检查:
public class Identifier<T extends Enum> {
public Identifier(T type, String value) {
}
}
,主要功能变为:
Identifier<Car.IdentifierType> carId = new Identifier<>(Car.IdentifierType.LICENSE_PLATE, "123 XYZ");
Identifier<Person.IdentifierType> personId = new Identifier<>(Person.IdentifierType.SOCIAL_SECURITY, "123456");
答案 0 :(得分:2)
public class Identifier<E extends Identifiable<? extends Enum>> {
public Identifier(Enum type, String value) {
//some code
}
}
可能足以满足您的需求
答案 1 :(得分:1)
你可以通过稍微调整一下代码来编译它,但我不确定它是你想要的。以下似乎对我有用。
Identifier<Car.IdentifierType, Car> carId =
new Identifier<Car.IdentifierType, Car>(Car.IdentifierType.LICENSE_PLATE,
"123 XYZ");
public static class Identifier<T extends Enum, E extends Identifiable<T>> {
public Identifier(T type, String value) {
// some code
}
}
问题是你为什么要这样做?如果您在后台编辑问题,我可以编辑我的答案以获得更多帮助。