At runtime this returns me a Class instance:
public static Class<?> getGenericClassOfType(Object object){
Class<?> clazz = (Class<?>) ((ParameterizedType) object.getClass() .getGenericSuperclass()).getActualTypeArguments()[0];
return clazz;
}
and afterwards I can initiate it with:
public static <T> T getDefaultInstance(Class<T> clazz) throws IllegalAccessException, InvocationTargetException, InstantiationException {
T instance = null;
Constructor<T>[] constructors = (Constructor<T>[]) clazz.getDeclaredConstructors();
Constructor<T> constructor = null;
for (Constructor cstr : constructors) {
//Only if default constructor
if (cstr.getParameters().length == 0) {
constructor = (Constructor<T>) cstr;
break;
}
}
if (constructor != null) {
constructor.setAccessible(true);
instance = constructor.newInstance();
}
return instance;
}
so the code in my base constructor looks like:
public abstract class BaseScene<T extends SceneController> {
private final static Logger LOGGER = LogManager.getLogger(BaseScene.class);
private final T sceneController;
//public T getSceneController() {
// return sceneController;
//}
protected BaseScene(){
T newInstance = null;
try {
Class<T> clazz = (Class<T>)ReflectionHelper.getGenericClassOfType(this);
newInstance = ReflectionHelper.getDefaultInstance(clazz);
} catch (IllegalAccessException | InvocationTargetException | InstantiationException e) {
LOGGER.error("Error while trying to initiate BaseScene",e);
}
sceneController = newInstance;
}
}
which works perfectly as I tested it.