关于java泛型问题,求赐教

ioscoder 2018-01-27 06:06:11
先上代码:



import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.lang.annotation.Annotation;
import java.lang.reflect.Type;

import okhttp3.ResponseBody;
import retrofit2.Converter;
import retrofit2.Retrofit;

public final class JsonConverterFactory extends Converter.Factory {

public static JsonConverterFactory create() {
return new JsonConverterFactory();
}

private final Gson gson;

private JsonConverterFactory() {
this.gson = new Gson();
}

@Override
public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {

return value -> {
String json = value.string();
Type resultType = new TypeToken<Result<IpInfo>>() {}.getType();
Result<IpInfo> result = gson.fromJson(json, resultType);
if (result.code == 0) {
return result.data;
}
else {
throw new RuntimeException("code: " + result.code);
}
};
}
}

public final class Result<T> {
public int code;
public T data;
}


就是这一行

Type resultType = new TypeToken<Result<IpInfo>>() {}.getType();

这里我不想写死IpInfo,这个函数的参数type其实就是IpInfo类型,但是这里我不知道怎么才能获得Result<type>的类型
求赐教,十万火急!


...全文
562 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
ioscoder 2018-02-01
  • 打赏
  • 举报
回复
自问自答,已解决:

public final class JsonConverterFactory extends Converter.Factory {

    public static JsonConverterFactory create() {
        return new JsonConverterFactory();
    }

    private final Gson gson;

    private JsonConverterFactory() {
        this.gson = new Gson();
    }

    @Override
    public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {

        return value -> {
            String json = value.string();
            Type resultType = new ParameterizedType() {
                @Override
                public Type[] getActualTypeArguments() {
                    return new Type[] { type };
                }

                @Override
                public Type getRawType() {
                    return Result.class;
                }

                @Override
                public Type getOwnerType() {
                    return null;
                }
            };

            Result result = gson.fromJson(json, resultType);
            if (result.code == 0) {
                return result.data;
            }
            else {
                throw new RuntimeException("code: " + result.code);
            }
        };
    }
}

80,351

社区成员

发帖
与我相关
我的任务
社区描述
移动平台 Android
androidandroid-studioandroidx 技术论坛(原bbs)
社区管理员
  • Android
  • yechaoa
  • 失落夏天
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧