peholmst / MVP4Vaadin

A small Model-View-Presenter addon for Vaadin applications
19 stars 7 forks source link

Patch for AbstractView #20

Open pgaschuetz opened 12 years ago

pgaschuetz commented 12 years ago

Hi,

here's a replacement for AbstractView.createPresenter(), which uses reflection to determine and create the Presenter

@Override
public P createPresenter() {

    ParameterizedType thisType = (ParameterizedType) getClass().getGenericSuperclass();

    @SuppressWarnings("unchecked")
    Class<P> presenterClazz = (Class<P>) thisType.getActualTypeArguments()[1];

    try {
        Constructor<P> ctor = presenterClazz.getConstructor();
        return ctor.newInstance();
    } catch (NoSuchMethodException e) {
        throw new UnsupportedOperationException(
                "No default constructor for Presenter '" + presenterClazz.getSimpleName() + "' available.");
    }
    catch (Exception e) {
        throw new RuntimeException(e);
    }
}
pgaschuetz commented 12 years ago

Sorry, here's a version that calls the correct constructor

@Override
@SuppressWarnings("unchecked")
public P createPresenter() {

    ParameterizedType thisType = (ParameterizedType) getClass().getGenericSuperclass();

    Class<V> viewClazz = (Class<V>) thisType.getActualTypeArguments()[0];
    Class<P> presenterClazz = (Class<P>) thisType.getActualTypeArguments()[1];

    try {
        Constructor<?> ctor = presenterClazz.getConstructor(viewClazz);
        return (P) ctor.newInstance(this);
    } catch (NoSuchMethodException e) {
        throw new UnsupportedOperationException(
                "No default constructor for Presenter " + presenterClazz.getSimpleName() + " available.");
    }
    catch (Exception e) {
        throw new RuntimeException(e);
    }
}