泛型:确保参数的类型相同

发布于 2025-01-06 12:19:25 字数 386 浏览 1 评论 0原文

我有以下方法:

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

我想确保两个参数的类型相同。如果当您尝试传递两种不同类型的参数时出现编译器错误,那就太酷了。

上面的方式显然不是正确的方式。我可以放入一个String 和一个Integer,因为它们都是从Object 扩展的。

我的愿望可能实现吗?或者是确保两个参数具有相同类型的唯一方法,以便在方法内检查它并抛出 IllegalArgumentException

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

眼眸印温柔 2025-01-13 12:19:25

如果您认为 S 是正确的类型,则可以这样做:

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

您可以也不能输入这些:

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

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

您可以这样做:

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

并像这样使用它

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

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

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
    }
}
﹏半生如梦愿梦如真 2025-01-13 12:19:25

恐怕这实际上是不可能的,除非进行明确的检查。它总是会被强制为 Object;没有办法阻止输入被强制为超类型。

您可以在参数验证中使用显式的基于反射的检查,但这只是您唯一的选择。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文