I have a Factory that makes an List. I have three Create methods. The first create method makes a list with Objects. It get the Information from the other two Create methods while the second get the Class from the type T and passes the class type to the third create method which create a new instance and return it.
That's my Factory
public class Factory {
public <T extends IPrototype<T>> List<T> create(T prototype, int n) throws Exception {
ArrayList<T> list = new ArrayList<>();
for(int j=0; j<n; j++)
list.add(create(prototype));
return list ;
}
public <T extends IPrototype<T>> T create(T prototype) throws Exception {
return (T) create(prototype.getClass());
}
public <T extends IPrototype<T>> T create(Class<T> type) throws Exception {
T obj = (T) type.newInstance();
return obj;
}
}
That's my IPrototype Interface
public interface IPrototype<T extends IPrototype<T>> {
}
The List can Only have object which implements IPrototype
public class Bar implements IPrototype<Bar>{
public Bar() {}
}
My Question is i get a Warning in the second create method.
public <T extends IPrototype<T>> T create(T prototype) throws Exception {
return (T) create(prototype.getClass());
}
/*Or method in long way */
public <T extends IPrototype<T>> T create(T prototype) throws Exception {
Class<T> cl = (Class<T>) prototype.getClass();
return (T) create(cl);
}
Type safety: Unchecked invocation create(Class) of the generic method create(Class) of type Factory
How i can handle this Warnings ?
That's the Main
public class Main {
public static void main(String[] args) throws Exception {
Factory factory = new Factory();
Foo prototype1 = new Foo();
Bar prototype2 = new Bar();
Foo inst = (Foo) factory.create(prototype1); // one Foo instance
List list = factory.create(prototype2,10); // ten Bars in List
List list2 = factory.create(prototype1, 10);
System.out.println(list);
System.out.println(list2);
}
}