【发布时间】:2014-10-26 03:35:43
【问题描述】:
我有一个实现类,它捕获接口方法的所有声明的异常。当我在类中注入和使用接口实例变量并希望调用实现方法时 - 我自然会得到一个编译器错误,指出我需要抛出/捕获父级中声明的异常。
我想到的选项很少,但我不喜欢它们。只是想知道解决这个问题的最佳方法。
- 将接口实例强制转换为 impl
- 使用无异常方法创建子接口
- 可能只是没有在接口中声明异常。只需在 impl 中捕获所有可能的异常。
编辑 1:附加一些示例代码
public interface ServiceUtilInterface {
public abstract String getMessage(String ID) throws CustomException;
}
@Component(value="MyServiceUtil")
public class MyServiceUtil implements ServiceUtilInterface {
@Override
public String getMessage(String ID) {
try{
//do something
}catch(CustomException e){
}
return "";
}
@Component
public class Usage {
@Autowired
ServiceUtilInterface serviceUtil;
public void someMethod(){
serviceUtil.getMessage("123");
//This where compiler expects me to throw /catch the exception defined in interface
}
}
【问题讨论】:
-
用一些代码解释会帮助我们
-
用一些代码编辑了我的问题。谢谢
标签: java spring interface dependency-injection