Compiler error using java generics with a list as a method parameter and throws a generic exception
I am getting compiler error when using generics in my project. I am generating 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 Concrete Class Manager
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 sortAll method without method parameters (sortAll ()) in the interface and it compiles using only the exception in the interface, also works, but using as not.
Thank.
source to share
As for the method sortAll(List<T> list)
, you should do:
@Override
public <E extends Exception> List<T> sortAll(List<T> array) throws E {
// TODO Auto-generated method stub
return null;
}
and then when calling the method, explicitly set the type-parameter methods:
try {
new MyConcreteManager().<IOException>sortAll(...);
} catch (IOException e) {
}
The compilation sortAll3()
compiles fine because in Java, when a method definition overrides another, it is not allowed to throw additional checked exceptions, but it may cause less.
source to share