简体   繁体   English

方法签名泛型中的java对此进行了扩展

[英]java in method signature generics extends from this

This does not work because of this.class it must be Tower , but I want that all classes that extends from Tower are assignable from the current Tower like ArrowTower or something else. 由于this.class它必须是Tower ,因此这是行不通的,但是我希望从Tower扩展的所有类都可以从当前Tower分配,例如ArrowTower或其他东西。

public Tower upgrade(Class<? extends this.class> c) {
    try {
        return c.getConstructor().newInstance();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

I can check it so, but I want that the complier says you thats the wrong extends hierarchy or something else 我可以检查一下,但是我希望编译器告诉您,那是错误的扩展层次结构或其他原因

if (!this.getClass().isAssignableFrom(c))
{
    return null;
}

I want it so because there are an ArrowTower and a FireArrowTower that are extends from ArrowTower and there are a CannonTower and a FireCannonTower that are extends from CannonTower . 我想它,是因为有一个ArrowTowerFireArrowTower是从扩展ArrowTower并有CannonTowerFireCannonTower是从延伸CannonTower But if want to upgrade an ArrowTower its possible to upgrade it to an CannonTower , but this should not be allowed. 但是,如果要升级ArrowTower可以将其升级为CannonTower ,但这是不允许的。

See: 看到:

    Tower t1 = new ArrowTower();
    t1 = t1.upgrade(FireArrowTower.class);

    Tower t2 = new CannonTower();
    t2 = t2.upgrade(Tower.class); // Here it musst be an Error

Sorry for my bad english I'm from Germany :D 对不起,我的英语不好,我来自德国:D

This is impossible due to the principle that, loosely speaking, a subclass should support everything the superclass supports (see also the Liskov substitution principle). 松散地说,子类应该支持超类所支持的所有内容(另请参见Liskov替换原理),这是不可能的。

Let me illustrate. 让我举例说明。 With the structure you describe, you want the compiler to accept: 使用您描述的结构,您希望编译器接受:

Tower myTower = new Tower();
myTower.upgrade(ArrowTower.class)

.. but not: .. 但不是:

GunTower myTower = new GunTower();
myTower.upgrade(ArrowTower.class);

right? 对? That would cause trouble, though. 但这会造成麻烦。 Look: 看:

Tower myTower = new GunTower();
myTower.upgrade(ArrowTower.class);

Here we only made the type of 'myTower' a bit less specific, and now you'd like the compiler to suddenly disallow this call. 在这里,我们仅使“ myTower”的类型不太具体,现在您希望编译器突然禁止此调用。 That's surprising, and indeed Java doesn't allow it. 令人惊讶的是,实际上Java不允许这样做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM