Java 将抽象类中的泛型属性定义为实现类的类型
假设我有一门课,比如:Java 将抽象类中的泛型属性定义为实现类的类型,java,c#,generics,Java,C#,Generics,假设我有一门课,比如: public abstract class Foo { public List<TypeOfImplementingClassHere> container; } 所以当另一个类实现它时,比如说: public class Bar extends Foo { public Bar(List<Bar> container) { this.container = container; } } 我们可以有一个指
public abstract class Foo {
public List<TypeOfImplementingClassHere> container;
}
所以当另一个类实现它时,比如说:
public class Bar extends Foo {
public Bar(List<Bar> container) {
this.container = container;
}
}
我们可以有一个指向在其中找到Bar对象的容器的指针。你能用Java或C来做这件事吗?当然
试试这个
public abstract class Foo<T extends Foo<T>> {
public List<T> container;
protected Foo() {
enforceConstraints();
}
private void enforceConstraints() {
boolean valid = true;
try {
valid =
((ParameterizedType) this.getClass().getGenericSuperclass())
.getActualTypeArguments()[0]
.equals(
this.getClass()
);
} catch (ClassCastException cce) {
valid = false;
}
if (!valid) {
String name = this.getClass().getSimpleName();
throw new IllegalImplementationException(
name + " must be declared as "+ "\"class " + name + " extends Foo<"+name+">\"");
}
}
private static class IllegalImplementationException extends RuntimeException {
IllegalImplementationException(String message) {
super(message);
}
}
}
在C语言中更简单:
public class Foo<T> where T : Foo<T> {
public List<T> container;
protected Foo() {
enforceConstraints();
}
private void enforceConstraints() {
if (!this.GetType().Equals(typeof(T))) {
String name = this.GetType().Name;
throw new IllegalImplementationException(
name + " must be declared as " + "\"class " + name + " : Foo<" + name + ">\"");
}
}
}
public class IllegalImplementationException : Exception {
public IllegalImplementationException(String message) : base(message) {}
}
enforceConstraints可以在发送到生产时删除。请注意,这强制以我们的方式通过反射来限定泛型参数,因为这里需要的类型边界在Java或C中不可用。因为我们完全通过反射来强制约束,所以没有必要添加约束t extends Foo,但这可以防止误用。请注意,使用约束FooUmm。。。你能更具体地说明你想做什么吗?这段代码毫无意义,不是Java开发。这个问题在被问及一个半月后被编辑为与Java相关。我下面的回答是当这被标记并作为C问题提问时。。我想这就是为什么你现在,就在今天。。投了反对票。@SimonWhitehead投了反对票,因为它不能解决问题。这个问题我已经讨论了一段时间,现在才解决。不管是Java还是C,都没有解决方案。