重载采用通用类型的方法会导致模棱两可的方法调用编译错误 [英] Overloading a method which takes in Generic type causes ambiguous method call compile error

查看:39
本文介绍了重载采用通用类型的方法会导致模棱两可的方法调用编译错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请参见以下简单代码段:

See below simple snippet:

public class GenericsOverloadingDistinguish<T> {
    public void print1(T t) {
        System.out.println("t");
    }

    public void print1(Integer i) {
        System.out.println("integer");
    }
}
public static void main(String[] args) {
    new GenericsOverloadingDistinguish<Integer>().print1(new Integer(1));
}

这将导致模棱两可的方法调用,并且无法编译.

This would cause an ambiguous method call and will not compile.

这完全使该类的用户感到困惑.它不能简单地调用 print1(T t) print1(Integer i),因为它不幸地使用了 Integer 作为通用类型.

This is utterly confusing on the user of that class. It is not able to call neither print1(T t) nor print1(Integer i) simple because it unfortunately used Integer as the generic type.

我了解泛型是在编译时进行的,并且具有类型擦除功能,但是Java不能防止此类错误吗?
如果给出了 GenericsOverloadingDistinguish 类并且不能更改该怎么办,而我只需要调用 print1(T t) T 为整数?

I understand generics is compile-time and there is type erasure, but doesn't Java have something to prevent such errors?
What if the GenericsOverloadingDistinguish Class is given and can't be changed, and I just need to invoke print1(T t) with T being an Integer?

推荐答案

如果提供了该类,那么您很不走运,没有解决该问题的好方法.

If the class is given, you're out of luck, there are no nice ways to resolve the problem.

在这种情况下,您如何猜测设计人员希望调用哪种方法?你根本做不到.现在想想编译器如何完成这项工作?

How would you guess which method the designer expected to be called in this case? You simply can't. Now think of how the compiler could do the job?

用这种语言可以做的是,如果可以给type参数赋予一个冲突值,则根本不允许这种重载.为什么还没有完成,这是一个很好的问题,但很难回答.可能被认为过于严格.

What could've been done in the language is to not allow this kind of overloading at all if the type parameter can be given a conflicting value. Why it hasn't been done is a good question but difficult to answer. It was probably deemed too restrictive.

无论如何,如果绝对需要,您可以像这样解决此问题:

Anyway, if you absolutely must, you can work around this problem like this:

GenericsOverloadingDistinguish<Integer> t = new GenericsOverloadingDistinguish<Integer>();
((GenericsOverloadingDistinguish)t).print1((Object)new Integer(1)); //prints "t"
((GenericsOverloadingDistinguish)t).print1(new Integer(1)); //prints "integer"

之所以可行,是因为 print1(T)的类型擦除是 print1(Object).

This works, because the type erasure of print1(T) is print1(Object).

不用说,这是一个很难看的错误,您确实不应该使用原始类型,但这是处理不良情况的最简单的方法.

Needless to say, this is bug ugly, and you really shouldn't be using raw types, but this is the least messy way of dealing with a bad situation.

这篇关于重载采用通用类型的方法会导致模棱两可的方法调用编译错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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