在 抽象泛型類中,通常會自動將數據轉換操做實現,使用者就不用關心數據轉換過程,專一業務處理就好了java
從新實現TypeReference<T>類中_type獲取的實現,這裏是基於jackson的實現示例,JsonUtil工具類是對jackson的實現,這裏就不提供了,其餘json轉換實現方法相似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; } } }