避免捕获通用异常并使用通用接口

时间:2018-07-18 05:33:43

标签: java oop generics exception exception-handling

我有一个要求,我有一个通用接口将一个实体转换为另一个实体

public interface Converter<T,U>{
    public U convert(T src) throws Exception;
}

实现类为

class StringToIntConverterImpl implements Converter<String,Integer>{
    public Integer convert(Integer i) throws StringConversionException;
}

现在在我的代码中,我使用

public class AppClass{
    private Converter<String,Integer> converter;
    public static void mainAppLogic(){
        try{
            converter.convert(input);
        }
        catch(Exception e){
        }
    }
}

在这里,我必须捕获通用Exception,如何避免这种情况?同时,我想在我的mainapp中使用Converter转换器decalartion而不是特定的ConverterClass,因为我想编程以进行接口连接,以便以后可以转换Converter的任何实现。

1 个答案:

答案 0 :(得分:0)

您可以使用通用异常:

public interface Converter<T, U, E extends Throwable> {
    U convert(T t) throws E;
}

现在,在您的主要方法中,您可以:

public class AppClass{
    private Converter<String,Integer,RuntimeException> converter;
    public static void mainAppLogic(){
        converter.convert(input);
    }
}
相关问题