Generics: Make sure parameters are of same type

折月煮酒 提交于 2019-12-06 03:47:54

You can do that if you consider that S is the correct type :

protected <S, T extends S> void setValue(final S oldValue, final T newValue) {
    // Do something
}

You can and can't input these :

// Works
setValue("something", "something");
setValue(new Object(), new String());

// Doesn't work
setValue(new String(), new Object());

or

You can do :

protected <S> void setValue(final S oldValue, final S newValue, final Class<S> clazz) {
    // Do something
}

and use it like that

setValue("something", "something", String.class);

or

protected <S> void setValue(final S oldValue, final S newValue) {
    if(!oldValue.getClass().equals(newValue.getClass())) {
        //throw something
    }
}

This isn't really possible, I'm afraid, except for explicit checks. It'll always get coerced up to Object; there's no way to stop inputs from getting coerced up to supertypes.

You can use explicit reflection-based checking in your argument validation, but that's just about your only option.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!