Yet another generics question: Needs unchecked conversion to conform to ...
I spent a lot of time massaging the code below to avoid a warning,
without success.
I pasted a sample class and inner classes that shows what I want to do.
I wrote two versions of a factory method: one that does not generate
any warnings, and the other generates one.
The return type of the second method is defined like this:
BeanFactory<Bean> createFactory2(String className){
...
}
The returned BeanFactory is also parametized, and this is where my
problem lies. Can anyone suggest how to avoid the warning, besides
adding a @suppresswarning annotation?
public class Generics {
public BeanFactory createFactory1(String beanClass)
throws Exception{
Class<?> bc = Class.forName(beanClass);
Class<? extends BeanFactory> bfc =
bc.asSubclass(BeanFactory.class);
Constructor<? extends BeanFactory> cstr =
bfc.getConstructor(new Class[]{});
return cstr.newInstance(new Object[]{});
}
public BeanFactory<Bean> createFactory2(String beanClass)
throws Exception{
Class<?> bc = Class.forName(beanClass);
Class<? extends BeanFactory> bfc =
bc.asSubclass(BeanFactory.class);
Constructor<? extends BeanFactory> cstr =
bfc.getConstructor(new Class[]{});
// The following line causes the warning:
return cstr.newInstance(new Object[]{});
}
public class BeanFactory<T extends Bean>{
}
public class Bean{
}
}