Ondra Žižka
Ondra Žižka

Reputation: 46796

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".

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?

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)?

Upvotes: 0

Views: 367

Answers (2)

thSoft
thSoft

Reputation: 22660

That's the best you can do. If you want to return this (which implements OriginWise), don't forget to let T extend OriginWise. See also this answer and http://passion.forco.de/content/emulating-self-types-using-java-generics-simplify-fluent-api-implementation.

Upvotes: 0

NimChimpsky
NimChimpsky

Reputation: 47290

default implementations in interfaces

I don't understand the rest of the question, as the code looks good to me.

Upvotes: 1

Related Questions