我们说我有一个类:
public abstract class Foo {
public List<TypeOfImplementingClassHere> container;
}
所以当另一个类实现它时,比如说:
public class Bar extends Foo {
public Bar(List<Bar> container) {
this.container = container;
}
}
我们可以有一个指向我们找到Bar
对象的容器的指针。你能用Java或C#吗?
答案 0 :(得分:0)
不确定
试试这个。
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<T>
,但这可以防止滥用。请注意,使用约束Foo<T extends Foo<T>
,您可以拥有Bar1 extends Foo<Bar1>
和Bar2 extends Foo<Bar1>
,但我们不需要第二种类型,因此需要进行反射。