java - Use the type parameter of the object in a default interface method -


i want compose 2 codecs (code below) together, must have compatible types fit together. code works had use line codec<f,t> c = this; work otherwise compiler didn't seem understand correctly type parameters (and restrictions on codec2). i'm glad code compiles there cleaner way achieve this?

/**  * represents coder-decoder format f format t  */ public interface codec <f,t> {     t encode(f obj);     f decode(t obj);      /**      * compose 2 codecs types <f,t> , <t,e> codec type <f,e>.      * @param codec2 second codec      * @return new codec      */     public default <e> codec<f,e> compose(codec<t,e> codec2) {         codec<f,t> c = this;         return new codec<f,e>() {             public e encode(f obj) { return codec2.encode(c.encode(obj)); }             public f decode(e obj) { return c.decode(codec2.decode(obj)); }         };     } } 

you're declaring anonymous inner class implements codec interface.

return new codec<f,e>() {     public e encode(f obj) { return codec2.encode(c.encode(obj)); }     public f decode(e obj) { return c.decode(codec2.decode(obj)); } }; 

within body of anonymous class declaration, this refers instance of anonymous inner class, ie. of type codec<f, e>.

use codec.this refer instance of enclosing class (the interface in case).

public e encode(f obj) {     return codec2.encode(codec.this.encode(obj)); }  public f decode(e obj) {     return codec.this.decode(codec2.decode(obj)); } 

Comments

Popular posts from this blog

Fail to load namespace Spring Security http://www.springframework.org/security/tags -

sql - MySQL query optimization using coalesce -

unity3d - Unity local avoidance in user created world -