在 抽象泛型类中,一般会自动将数据转换操作实现,使用者就不用关心数据转换过程,专注业务处理就行了
重新实现TypeReference<T>类中_type获取的实现,这里是基于jackson的实现示例,JsonUtil工具类是对jackson的实现,这里就不提供了,其他json转换实现方法类似
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import com.bc.core.util.JsonUtil;
import com.fasterxml.jackson.core.type.TypeReference;
public abstract class BaseTopicMsgHandle<T> {
public abstract String topic();
public abstract void handle(T data);
public void jsonHandle(String json) {
T obj = toObject(json);
if (obj == null) {
return;
}
handle(obj);
}
protected TypeReferenceT typeReferenceT = new TypeReferenceT();
public T toObject(String json) {
return JsonUtil.toObject(json, typeReferenceT);
}
private class TypeReferenceT extends TypeReference<T> {
protected final Type _type;
TypeReferenceT() {
Type superClass = BaseTopicMsgHandle.this.getClass().getGenericSuperclass();
if (superClass instanceof Class<?>) {
throw new IllegalArgumentException(
"Internal error: TypeReference constructed without actual type information");
}
_type = ((ParameterizedType) superClass).getActualTypeArguments()[0];
}
@Override
public Type getType() {
return _type;
}
}
}