I try to create storage for my PageFactory in the follow way:
private static Map<Class<? extends BasePage>, ? extends BasePage> pageStore = new HashMap<>();
@SneakyThrows
public <T extends BasePage> T getPage(Class<T> pageClazz) {
T t = pageClazz.getDeclaredConstructor().newInstance();
pageStore.put(pageClazz, t);// <---- here is compilation error
return null;
}
So, from the part of code you can understand where I have the compilation error, although both ?
and T
extended from the BasePage
:
Required type: capture of ? extends BasePage do not math to the generic
Provided: T
Do I have to change type from <? extend BasePage>
to the BasePage
or I can save current logic and cast my object in the another way?
CodePudding user response:
You get this because you most likely have a common misconception of what the meaning of wildcards is in Java generics.
The type ? extends BasePage
for the values of the map does not mean that you can put objects of different types that extend BasePage
as values in this map.
It means: the type of the values in this map is a specific, but unknown type that extends BasePage
.
You cannot put any values into such a map, because the type that the values are supposed to have, is unknown. When you try to put a value in such a map, there is not enough information for the compiler to check that the value you are adding has the correct type, because the compiler doesn't know what the specific type is that the ?
stands for.
It's exactly the same as why you cannot add anything to a List<?>
.
If you need to store objects of different types that are all subtypes of BasePage
, then the right solution is indeed to use BasePage
instead of ? extends BasePage
for the type of the values of the map.
CodePudding user response:
You can change the pageStore
HashMap to use BasePage
in the value and add to the map by using inheritance relationship because any divided class will have BasePage
parent
private static Map<Class<? extends BasePage>, BasePage> pageStore = new HashMap<>();
public <T extends BasePage> T getPage(Class<T> pageClazz) throws Exception {
T t = pageClazz.getDeclaredConstructor().newInstance();
pageStore.put(pageClazz, t);
return t;
}