I am stuck with a strange problem due to java generics "extend" keyword. I have developed a generic method to get the elements from a method as generic as possible.
When I use <? extends X>
, I am not able to add any elements to it.
In my case I am using the generic template to restrict the arguments provided by the user and providing the return type ac.
class Root{
}
class Sub_1 extends Root{
}
class Sub_2 extends Root{
}
public static <T extends Root> List<T> getSubElements(Class<T> targetClass){
List<T> ls=new ArrayList<>();
if(targetClass.getSimpleName().equals("Sub_1")){
Sub_1 sub_1 = new Sub_1();
ls.add(sub_1);
}else if(targetClass.getSimpleName().equals("Sub_2")){
Sub_2 sub_2=new Sub_2();
ls.add(sub_2);
}
return ls;
}
In the above case, I am getting compilation error when I add elements to the list.
ls.add(sub_1);
ls.add(sub_2);
It looks quite challenging now to solve this issue.. I will be happy if someone can provide some hints here.
Thanks!!
`public static void main(String[] args){ List