Reputation: 33
I'm getting a Compiler error when using generics in my project. I generate a sample code:
My Bean Interface
package sample;
public interface MyBeanInterface {
Long getId();
String getName();
}
My Bean Concrete Class
package sample;
public class MyBean implements MyBeanInterface {
private Long id;
private String name;
@Override
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@Override
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
My Manager Interface
package sample;
import java.util.List;
public interface MyManagerInterface<T extends MyBeanInterface> {
<EXCEPTION extends Exception> List<T> sortAll(List<T> array) throws EXCEPTION;
List<T> sortAll2(List<T> array);
<EXCEPTION extends Exception> List<T> sortAll3() throws EXCEPTION;
}
My Manager Concrete Class
package sample;
import java.io.IOException;
import java.util.List;
public class MyConcreteManager implements MyManagerInterface<MyBean> {
@Override
//this fails
public List<MyBean> sortAll(List<MyBean> array) throws IOException {
return null;
}
@Override
//this works
public List<MyBean> sortAll2(List<MyBean> array) {
return null;
}
@Override
//this works
public List<MyBean> sortAll3() {
return null;
}
}
I tried using the method sortAll with no method parameters (sortAll()) in the interface and it compiles, using only the exception in the interface also works, but using both not.
Thanks.
Upvotes: 3
Views: 90
Reputation: 62864
With regards to the sortAll(List<T> list)
method, you have to do:
@Override
public <E extends Exception> List<T> sortAll(List<T> array) throws E {
// TODO Auto-generated method stub
return null;
}
and then, when invoking the method to explicitly set the methods type-parameter:
try {
new MyConcreteManager().<IOException>sortAll(...);
} catch (IOException e) {
}
The sortAll3()
implementation compiles fine, because in Java, when a method definition overrides another one, it is not allowed to throw additional checked exceptions, but it may throw fewer.
Upvotes: 2