Either I’m too stupid to use google, or nobody else encountered this problem so far.
I’m trying to compile the following code:
public interface MyClass {
public class Util {
private static MyClass _this;
public static <T extends MyClass> T getInstance(Class<T> clazz) {
if(_this == null) {
try {
_this = clazz.newInstance();
} catch(Exception e) {
e.printStackTrace();
}
}
return _this;
}
}
}
Howerer, in the line “return _this;” I get the error “Type mismatch: cannot convert from MyClass to T”
Why is this? T extends MyClass, so where is the problem? If I change the line to “return (T)_this;”, i just get a warning about the unchecked cast, but I don’t like warnings 😉 Is there a way to achieve what i want without an error or warning?
Imagine you have two implementations of
MyClass,FooandBar. As a field of typeMyClass,_thiscould be aFooor aBar.Now, since your
getInstancemethod returns<T extends MyClass>, it’s legal to call it any of these ways:This doesn’t work if it’s the first call, because
MyClassis an interface and can’t be instantiated withnewInstance().Now, what would happen if
_thiswas an instance ofFooand you calledUtil.getInstance(Bar.class)? That’s why you aren’t allowed to do this.