Here is my code using Guava:
public interface NetSession {
void connect();
}
public interface HttpSession extends NetSession {
void useRestApi();
}
class HttpSessionImpl implements HttpSession {
}
class Test {
NetSession makeProxy(NetSession session) {
TypeToken<? extends NetSession> sessionTT = TypeToken.of(session.getClass());
TypeToken<? extends NetSession>.TypeSet ifaces = sessionTT.getTypes().interfaces();
// here we looking for real <? extends NetSession> interface
Class<? extends NetSession> sessionIface = (Class<? extends NetSession>) ifaces.stream()
.filter(i -> i.isSubtypeOf(NetSession.class))
.map(i -> i.getRawType())
.findAny().orElse(null);
assert sessionIface != null;
session.connect();
if (sessionIface == NetSession.class) {
return session; // as is
}
// make extra
HttpSession httpSession = (HttpSession) session;
httpSession.useRestApi();
}
}
My question is: is there more elegant way to find Class of interface by its super? i mean something like:
Class<? extends NetSession> sessionIface = sessionTT.getInterfaceExtending(NetSession.class);
assert sessionIface == HttpSession.class; // is ok in case above
With Guava or else make no difference.
Aucun commentaire:
Enregistrer un commentaire