@@ -81,6 +81,24 @@ public void setConnectionId(int connectionId) {
8181 this .connectionId = connectionId ;
8282 }
8383
84+ @ Override
85+ public <T > T unwrap (Class <T > iface ) {
86+ try {
87+ if (isWrapperFor (iface )) {
88+ return iface .cast (this );
89+ } else {
90+ throw new RuntimeException ("The context is not a wrapper for " + iface .getName ());
91+ }
92+ } catch (Exception e ) {
93+ throw new RuntimeException ("The context is not a wrapper and does not implement the interface" );
94+ }
95+ }
96+
97+ @ Override
98+ public boolean isWrapperFor (Class <?> iface ) {
99+ return iface .isInstance (this );
100+ }
101+
84102 }
85103
86104 static class TestServerEventHandler implements TServerEventHandler {
@@ -99,12 +117,12 @@ public ServerContext createContext(TProtocol input, TProtocol output) {
99117 }
100118
101119 public void deleteContext (ServerContext serverContext , TProtocol input , TProtocol output ) {
102- TestServerContext ctx = (TestServerContext ) serverContext ;
120+ TestServerContext ctx = serverContext . unwrap (TestServerContext . class ) ;
103121 System .out .println ("TServerEventHandler.deleteContext - connection #" +ctx .getConnectionId ()+" terminated" );
104122 }
105123
106124 public void processContext (ServerContext serverContext , TTransport inputTransport , TTransport outputTransport ) {
107- TestServerContext ctx = (TestServerContext ) serverContext ;
125+ TestServerContext ctx = serverContext . unwrap (TestServerContext . class ) ;
108126 System .out .println ("TServerEventHandler.processContext - connection #" +ctx .getConnectionId ()+" is ready to process next request" );
109127 }
110128
0 commit comments