I got a task to rewrite application in Java EE and Java JSF. I decided to go with Spring Boot and Angular. Currently I am struggling with generics in Java.
I have abstract class Item and few classes which extends this class e.g.:
public class Item1 extends Item
public class Item2 extends Item
Then I have an abstract class managing these elements (every item has to be treated differently):
public abstract class ItemAdapter<ELT extends Item> {
private final Class<ELT> eltClass;
public boolean isMyElement(Item item) {
return eltClass.isAssignableFrom(item.getClass());
}
@Transactional
public abstract void add(ELT item);
}
and classes which extends this class:
public class Item1Adapter extends ItemAdapter<Item1>
public class Item2Adapter extends ItemAdapter<Item2>
When I receive List<Item> items I have to perform add method based on its type. So I have auxiliary class:
@Service
@AllArgsConstructor
public class AdapterSetService {
...
public List<ItemAdapter> getAllAdapters() {
return Arrays.asList(
item1Adapter,
item2Adapter,
);
}
public ItemAdapter getAdapterOfType(Item item) {
for (ItemAdapter adapter : getAllAdapters()) {
if (adapter.isMyElement(item)) {
return adapter;
}
}
throw new RuntimeException("Unknown type: " + item);
}
}
And what I do is:
for (Item item: items) {
ItemAdapter itemAdapter = adapterSetService.getAdapterOfType(item);
itemAdapter.add(item);
}
The problem is that I get warnings from IDE:
- In AdapterSetService.getAllAdapters method - "Raw use of parameterized class 'ItemAdapter'"
- In AdapterSetService.getAdapterOfType method - the same message
- When calling adapterSetService.getAdapterOfType - the same message
What I was trying to do:
- Changing AdapterSetService.getAllAdapters and AdapterSetService.getAdapterOfType to retun ItemAdapter<? extends Item> but then I get error when calling itemAdapter.add(item) - Required type: capture of ? extends Item Provided: Item
Any suggetions how to solve this?
List<ItemAdapter>— You have definedItemAdapterto accept a type argument (ELT extends Item). You haven't given one. This is called 'using raw types'. Never use raw types, always provide the type arguments.