Reputation: 695
I have an implementation class which catches all the declared exceptions of a method of an Interface. As I inject and use the Interface instance variable inside a class and hope to call the implementation method - I am naturally getting a compiler error pointing that I either need to throw/catch the exceptions declared in parent.
Few options that come to my mind are these, but I don't like them. Just want to know the best way to go about this.
EDIT 1: Attached some example code
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
}
}
Upvotes: 0
Views: 111
Reputation: 3146
UPDATE
Cast the interface instance to impl - never ever do that. If you use Spring then you never know what the implementation of an interface could be. This should be configuration dependent. If you start do write jUnits you will probably need to use mock (fake) components for testing. Then if you try to cast your mock to a concrete implementation your code will fail. In other words you will never be able to write proper unit tests. The other thing is that if you add some Aspects or make a service @Transactional or @Validated then you wont be able to cast because instead of your implementation you may receive a proxy object.
and 3 that strongly depends on your code design. Try to find some materials about good practices for throwing and handling exceptions. There are some general rules about that. Probably no one can help you with this because this is service specific.
Upvotes: 1