I have the following classes:
public abstract class ClassWithHelper<T extends HelperInterface> {
Class<T> helperClass;
protected T helper;
protected Gson gson = new GsonBuilder().create();
public void loadHelper(String helperString) throws InstantiationException, IllegalAccessException {
if (!Strings.isNullOrEmpty(helperString)) {
wizard = gson.fromJson(helperString, getHelperClass());
} else {
wizard = getHelperClass().newInstance();
}
}
protected abstract Class<T> getHelperClass();
}
public class ImplementingClass extends ClassWithHelper<HelperClass> {
@Override
protected Class<HelperClass> getHelperClass() {
return HelperClass.class;
}
}
Now, what is nice is that when I call implementingClass.helperClass, it automatically casts it to HelperClass. However, I am wondering if I really need to write and override getHelperClass. I can’t write helper.getClass (because it might be null), and I know the way I have it written there is a type erasure problem.
However, is there a way for me to rewrite my code to avoid having to state the helperClass in two ways and still have type inference for it?
Try this :