【问题标题】:Using a Generic to return correct class extracted from a Type使用泛型返回从类型中提取的正确类
【发布时间】:2017-03-16 07:21:20
【问题描述】:

我正在尝试从文件中加载由 JSON 编码的对象..

我可以每次只编写内联代码,但我想将保存/加载移动到静态实用程序类,但我不想在主代码中盲目地转换回对象。

所以我现在有

    public Class MyClass(){

    private List<Door> doors;
    private final Type type = new TypeToken<List<Door>>(){}.getType();


    private void load(){
            Gson gsondecoder = new Gson();
            File parent = new File ("saves");
            File file =  new File(parent,"doors.json");
            List<Door> doors= null;
            if (!parent.exists())return;
            if(!file.exists())return;
            try {
                InputStream in = new FileInputStream(file);
                InputStreamReader inread = new InputStreamReader(in);
                JsonReader reader = new JsonReader(inread);
                doors = gsondecoder.fromJson(reader,type);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
    }

所以我想搬到一个更像 公共类 MyClass(){

    private List<Door> doors;
    private final Type type = new TypeToken<List<Door>>(){}.getType();


    private void load(){
            File parent = new File ("saves");
            File file =  new File(parent,"doors.json");
            List<Door> doors= null;
            doors = (List<door>) Utility.load(file,type);
    }

我的问题是如何在不盲目投射的情况下返回正确的课程 即只是

door = Utility.load(file,type)

我的想法是

public class Utilities {

static Gson gsonencoder = new Gson();
/**
 * The objects class must much the TypeTokens underlying class.
 *
 * @param file
 * @param object
 * @param type
 */
public static void saveFile(File file, T object, TypeToken<T> type) {
    try {
        if (!file.exists()) file.createNewFile();
        OutputStream out = new FileOutputStream(file);
        String encoded = gsonencoder.toJson(object, type.getType());
        out.write(encoded.getBytes());
        out.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

public static T loadFile(File file, TypeToken<T> type){
    if(!file.exists())return null;
    T object = null;
    try {
        InputStream in = new FileInputStream(file);
        InputStreamReader inread = new InputStreamReader(in);
        JsonReader reader = new JsonReader(inread);
        object = gsonencoder.fromJson(reader,type.getType());
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    return object;

}}

但我显然在这里遗漏了如何正确使用泛型。

【问题讨论】:

  • 另外......投反对票的人......谁甚至懒得评论他投反对票的原因......干得好

标签: java generics


【解决方案1】:

您需要定义泛型类型 ()。将 loadFile 签名更改为:

public static <T> T loadFile(File file, TypeToken<T> type)

@见Generic Methods

【讨论】:

  • 感谢现在按预期工作......我不明白定义和返回类型之间的区别......或者至少明白它们是如何在签名中单独声明的
猜你喜欢
  • 2020-10-24
  • 2021-05-01
  • 2022-01-19
  • 2017-06-07
  • 1970-01-01
  • 2014-08-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多