Java泛型中的精确类型匹配 [英] Exact type match in Java generics

查看:54
本文介绍了Java泛型中的精确类型匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下Java代码有效-没有编译时或运行时错误.

The following Java code is valid - no compile- or run-time errors.

public class Test {
  public static void main(String[] args) {
    System.out.println(
      new Comparator<>("hello", 5).areEqual()
    );
  }

  private static class Comparator<T> {

    private final T left;
    private final T right;

    public Comparator(T left, T right) {
      this.left = left;
      this.right = right;
    }

    public boolean areEqual() {
      return left.equals(right);
    }
  }
}

我希望将"hello" 5 的值强制转换为作为常见父级的 Object .

I expect the values "hello" and 5 are casted to Object, which is a common parent.

是否有一种编写类的方式,使得传递相同类型的对象以外的其他类会导致编译时错误?IE.不允许将传递给共同祖先的物体传递出去.

Is there a way to write the class in such a way that passing other than objects of the same type causes a compile-time error? I.e. passing objects casted to a common ancestor not allowed.

推荐答案

不是,不是.

因为您的通用类型是未绑定的,所以只有一个共同的祖先: Object -您可以正确推测.

Because your generic type is unbound, there's only one common ancestor: Object - as you correctly surmise.

在这种情况下,您唯一可以做的就是确保为要通过此方法传递的对象正确定义 equals .您还需要处理将 null 作为参数传递的情况.

The only thing you can realistically do in this scenario is ensure that equals is correctly defined for objects you want to pass through this method. You would also want to handle cases in which you pass null as an argument, too.

这篇关于Java泛型中的精确类型匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆