I searched my use case and found interesting answers, but they are not suitable for me. What would be the appropriate way:
@SuppressWarnings("unchecked")
public <T> T newInstance(String name) throws ClassCastException, InstantiationException, IllegalAccessException, ClassNotFoundException {
return (T) loadClass(name).newInstance();
}
or a little different:
public <T> T newInstance(String name, Class<T> c) throws ClassCastException, InstantiationException, IllegalAccessException, ClassNotFoundException {
return c.cast(loadClass(name).newInstance());
}
I think both methods do the same. From my point of view, method 1 is better due to smaller parameters. Both throw a ClassCastException, which will be good for me. In truth, the annotation is @SuppressWarnings("unchecked")not very pleasant.
Can someone tell me if there are any advantages to one method for another?
Edit: Jon Skeet answer is correct. The following passage may provide further clarification.
public class Test {
public static void main(String[] args) {
Object o = new Object();
Test.<String>realCast(o, String.class);
}
private static <T> T realCast(Object o, Class<T> c) {
return c.cast(o);
}
}
realCast() , o c. , fakeCast() , T.