如何使用 guice 使用通用 jsonFile 处理程序?

how to use generic jsonFile handler using guice?

我有 2 个存储库 类:

public class ResponseRepository implements IRoutingResponseRepository {

    private final String baselineFileName;

    @Inject
    @Singleton
    public ResponseRepository(@Named("baseline_file") String baselineFileName) {
        this.baselineFileName = baselineFileName;
    }

    @Override
    public E2EResult getBaseLine() {
        E2EResult e2EResult = null;
        ObjectMapper mapper = new ObjectMapper();
        try
        {
            e2EResult =  mapper.readValue(new File(baselineFileName), E2EResult.class);
        } catch (JsonGenerationException e)
        {
            e.printStackTrace();
        } catch (JsonMappingException e)
        {
            e.printStackTrace();
        } catch (IOException e)
        {
            e.printStackTrace();
        }
        return e2EResult;
    }
}

public class StatsRepository implements IRoutingResponseRepository {

    private final String baselineFileName;

    @Inject
    @Singleton
    public StatsRepository(@Named("stats_file") String baselineFileName) {
        this.baselineFileName = baselineFileName;
    }

    @Override
    public StatsObj getStats() {
        StatsObj statsObj = null;
        ObjectMapper mapper = new ObjectMapper();
        try
        {
            statsObj =  mapper.readValue(new File(baselineFileName), StatsObj.class);
        } catch (JsonGenerationException e)
        {
            e.printStackTrace();
        } catch (JsonMappingException e)
        {
            e.printStackTrace();
        } catch (IOException e)
        {
            e.printStackTrace();
        }
        return statsObj;
    }
}

如何将通用代码重构为通用代码?

我还希望 guice 在 <E2EResult> 时使用 fileName = E2EResult.csv,在 <StatsObj>

时使用 fileName = StatsObj.csv

我试过:

但我写错了泛型。它显示错误。 而且我不确定如何让 guice 注入不同的文件名

public interface IFileHandler<T> {

    T getContent();
}

public class JsonFileHandler implements IFileHandler<T> {


    String fileName;

    @Inject
    public JsonFileHandler(String file) {
        this.fileName = file;

        //Constants.RESULTS_BASELINE_FILE
    }

    public <T> T getContent() {
        T t = null;
        ObjectMapper mapper = new ObjectMapper();
        try {
            t = mapper.readValue(new File(fileName), T.class);
        } catch (JsonGenerationException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return t;
    }
}

对于类型变量部分,使用此接口将是:

public interface IFileHandler<T> {
    T getContent();
}

此实现 class 声明和方法签名:

class JsonFileHandler<T> implements IFileHandler<T> {
    public T getContent() {
        T t = null;
        // ...
        return t;
    }
}