Tag: 嵌套generics

通用树,自有界generics

我要为我的一个项目添加通用性。 我喜欢generics,因为这会使我的代码更加健壮,自我记录并删除所有那些丑陋的演员。 然而,我遇到了一个棘手的案例,并试图表达我的一个结构的“递归”约束。 这基本上是某种“通用”树,具有双链接(对于孩子和父母)。 我最大限度地简化了课程以显示问题: public class GenericTree< ParentClass extends GenericTree, ChildClass extends GenericTree> { // Attributes private ArrayList children = new ArrayList(); private ParentClass parent = null; // Methods public void setParent(ParentClass parent) { this.parent = parent; } public void addChild(ChildClass child) { child.setParent(this); this.children.add(child); } } 问题出在指令: child.setParent(this) 。 Java给出以下错误: 绑定不匹配:ChildClass类型的方法setParent(?)不适用于 参数(GenericTree)。 通配符参数? […]

Java Generics Hell

我怀疑此处已被问过(并已回答),但我不知道如何命名问题。 为什么只有在我没有通过课程本身时才能表达通配符而没有问题? 这一切都归结为这段代码。 除了调用genericsHell(ShapeSaver.class)之外,一切都按预期工作: interface Shape { } interface Circle extends Shape { } interface ShapeProcessor { } class CircleDrawer implements ShapeProcessor { } class ShapeSaver implements ShapeProcessor { } class Test { void genericsHeaven(ShapeProcessor a) {} void genericsHell(Class<? extends ShapeProcessor> a) {} void test() { genericsHeaven(new CircleDrawer()); genericsHeaven(new ShapeSaver()); genericsHell(CircleDrawer.class); genericsHell(ShapeSaver.class); // ERROR: The […]

如何使嵌套通用参数系统正常工作?

所以我试图让一个相当复杂的系统工作。 这是我正在尝试的基础知识。 规则: abstract class Rule { // stuff } class ExampleRule extends Rule { // stuff } 处理程序: abstract class RuleHandler { Class clazz; RuleHandler(Class forClass) { this.clazz = forClass; } abstract void doStuff(T rule); } class ExampleRuleHandler extends RuleHandler { ExampleRuleHandler() { super(ExampleRule.class); } void doStuff(ExampleRule rule) { // stuff } } 把它们绑在一起: […]