在做mit6.824实验时,想用Java实现,逛了圈github发现已经有人实现了一部分:MIT 6.824-Java
其中关于RPC实现采用了netty,里面自己实现了Encode和Decode,创建了一个Class对象来接受序列化对象的类型,代码如下:
public class RpcEncoder extends MessageToByteEncoder {
private final Class<?> clazz;
private final RpcSerializer rpcSerializer;
public RpcEncoder(Class<?> clazz, RpcSerializer rpcSerializer) {
this.clazz = clazz;
this.rpcSerializer = rpcSerializer;
}
...
当我采用泛型去实现后:
public class RpcEncoderTest<T> extends MessageToByteEncoder<T>{
private final RpcSerializer rpcSerializer;
public RpcEncoderTest(RpcSerializer rpcSerializer) {
this.rpcSerializer = rpcSerializer;
}
...
出现了如下问题: 我还正纳闷呢,Java难道继承有泛型的父类后必须执行泛型吗?详细一看才知道,原来netty进行调用encode时会去检测当前的泛型: TypeParameterMatcher :
TypeParameterMatcher matcher = map.get(typeParamName);
if (matcher == null) {
matcher = get(find0(object, parametrizedSuperclass, typeParamName));
map.put(typeParamName, matcher);
}
因为Java的泛型擦除机制,导致泛型为null: find0:
private static Class<?> find0(
final Object object, Class<?> parametrizedSuperclass,
String typeParamName) {
final Class<?> thisClass = object.getClass();
Class<?> currentClass = thisClass;
......
currentClass = currentClass.getSuperclass();
if (currentClass == null) {
return fail(thisClass, typeParamName);
}
父类子类都为泛型均未指定,则currentClass为null,导致fail 在Github上也有对应的issues https://github.com/netty/netty/issues/1247 其中有这么一句话:
*HandlerAdapter has methods like acceptInboundMessage(…) so that you can tell the handler about the messages you are interested (and not interested). Netty implements that method dynamically by determining the type parameter of the handler.
也就是Netty需要动态的获取message类型来完成是否接收当前message等操作,所以继承MessageToByteEncoder必须指定类型
|