we can declare a method in Java as
public static <T extends ClassTakesA<A>, A extends ClassTakesBC<B, C>, B extends ClassB, C extends ClassC> T MyFunc(Class<T> clazz) {
T obj = null;
try {
obj = clazz.newInstance();
} catch (InstantiationException | IllegalAccessException e) {
e.printStackTrace();
}
return obj;
}
So that at compile time or in IDE we already know the parameter to MyFunc() must be bounded by T. This works great because
MyFunc(Object.class) // good, gives compile time error as expected
MyFunc(ClassTakesA.class) // good, although need @SuppressWarnings("unchecked")
Now if I need to declare the parameter to MyFunc() first, how should I declare it so that I can get compile time (or in IDE) error if the parameter is not bounded by T? e.g.
public static void main(String[] args) {
Class myClass = Object.class;
MyFunc(myClass); // no error at compile time, but failed in runtime
}
Tried this but its wrong syntax
Class<T extends ClassTakesA<A>, A extends ClassTakesBC<B, C>, B extends ClassB, C extends ClassC> myClass;
And by the way, how do you get rid of the @SuppressWarnings("unchecked")?
A suggestion was to use
Class<ClassTakesA> myClass = ClassTakesA.class;
But I do not allow passing
ClassTakesA<ClassZ> classTakesANot = new ClassTakesA<ClassZ>();
Class<ClassTakesA> myClass = classTakesANot.getClass();
MyFunc(myClass);
as ClassZ
does not extend ClassTakesBC<B, C>