简体   繁体   English

Java泛型,扩展泛型和抽象类

[英]Java Generics, extended Generics and abstract classes

I've got the following classes set up: 我已经设置了以下课程:

public abstract class Process<T,S> {
    ...
}

public abstract class Resource<T, S extends Process<T, S>> {
    protected S processer;
    ...
}

public class ProcessImpl<EventType1, EventType2> {
    ...
}

public class ResourceImpl extends Resource<EventType1, ProcessImpl> {
    processer = new ProcesserImpl();
    ...
}

Everything is fine until I get to the ResourceImpl . 一切都很好,直到我到达ResourceImpl I'm told that ProcessImpl is not a valid substitute for the bounded parameter <S extends Process<T,S>> of the type Resource<T,S> . 我被告知ProcessImpl不是有效参数<S extends Process<T,S>>Resource<T,S>的有效替代品。

I've tried various ways of getting around this and keep hitting a wall. 我已经尝试了各种方法绕过这个并继续撞墙。

Does anyone have any ideas? 有没有人有任何想法?

public class ProcessImpl<EventType1, EventType2> {
...
}

Because ProcessImpl doesn't extend Process. 因为ProcessImpl不扩展 Process。 Your ProcessImpl is not derived from Process, which is what you're declaring that parameter should be. 您的ProcessImpl不是从Process派生的,这就是您声明该参数应该是什么。

You might want to do something like this: 你可能想做这样的事情:

public abstract class Process<T, S> {
}

public abstract class Resource<T, S extends Process<T, S>> {
    S processor;

}

public class ProcessImpl extends Process<EventType1, ProcessImpl> {
}

public class ResourceImpl extends Resource<EventType1, ProcessImpl> {

}

If you constrain the S parameter of the Resource to be a processor you also need to properly declare it on the ProcessImpl class. 如果将ResourceS参数约束为处理器,则还需要在ProcessImpl类上正确声明它。 I don't know what EventType2 is but it should be implementing Process interface. 我不知道EventType2是什么,但它应该实现Process接口。 I assumed you actually want to say ProcessImpl . 我假设你真的想说ProcessImpl

I can't see a way to edit the original version, or comment on given answers without a better rep. 我看不到编辑原始版本的方法,或者在没有更好的代表的情况下对给定答案进行评论。

This code will exist on a web layer, the eventtype2 is defined on the persistence layer and accessible only in the core layer which exists below this level. 此代码将存在于Web层上,eventtype2在持久层上定义,只能在此级别下面的核心层中访问。

So unfortunately without having a tight coupling, which I would like to avoid, I don't have access to EventType2. 所以很遗憾没有紧密耦合,我想避免,我没有访问EventType2。

If you don't want your code to depend on some existing package, which contains the Process , you could also introduce some new interface package depending on nothing in the very bottom of the class hierarchy. 如果您不希望您的代码依赖于包含Process某个现有包,您还可以在类层次结构的最底层引入一些新的接口包,具体取决于任何内容。 (If you are able to change the constrains of the inheritance of course.) (如果你能够改变继承的约束。)

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

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