简体   繁体   English

Java泛型:使用接口应用于的类的类型?

[英]Java generics: Using the type of class an interface is applied to?

I have an interface, whose method could conveniently return the instance on which the method is called. 我有一个接口,该接口的方法可以方便地返回在其上调用该方法的实例。 For instance, a setter could return "this". 例如,设置员可以返回“ this”。

interface OriginWise<T> {
      T setOrigin( Origin origin );
}

Is there some way to get an instance of T automatically from the class it's applied to, without passing it as shown below? 有什么方法可以从应用的类中自动获取T的实例,而无需按如下所示传递它?

class MyBean implements OriginWise<MyBean> {
    MyBean setOrigin( Origin o ){ ...; return this; }
}

Also, what's the progress with default implementations in interfaces (methods which only use other interface's methods; not the same as abstract class)? 另外,接口的默认实现(仅使用其他接口方法的方法;与抽象类不同的方法)的进展如何?

default implementations in interfaces 接口中的默认实现

I don't understand the rest of the question, as the code looks good to me. 我不理解其余的问题,因为代码对我来说看起来不错。

That's the best you can do. 那是你所能做的最好的。 If you want to return this (which implements OriginWise), don't forget to let T extend OriginWise. 如果要返回此值(实现OriginWise),请不要忘记让T扩展OriginWise。 See also this answer and http://passion.forco.de/content/emulating-self-types-using-java-generics-simplify-fluent-api-implementation . 另请参见此 答案http://passion.forco.de/content/emulating-self-types-using-java-generics-simplify-fluent-api-implementation

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

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