Generics: Make sure parameters are of same type

我们两清 提交于 2019-12-07 14:41:03

问题


I've got the following method:

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

I want to make sure, that both parameters are of the same type. It would be cool, if there'd be a compiler error when you try to pass parameters of two different types.

The above way is clearly not the correct one. I can put into a String and an Integer, since the both extend from Object.

Is my want even possible? Or is the only way to make sure both parameters are of the same type to check it inside the method and throw an IllegalArgumentException?


回答1:


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
    }
}



回答2:


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.



来源:https://stackoverflow.com/questions/9299194/generics-make-sure-parameters-are-of-same-type

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