泛型方法重载 [英] Method overloading with generics

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

问题描述

在尝试创建两个静态重载方法时,出现编译错误.谁能解释一下?

Where I try to create two static overloading methods I got an compilation error. Can anyone explain this?

public class A {
 public static void a(Set<String> stringSet) {}
 public static void a(Set<Map<String,String>> mapSet) {}
}

推荐答案

原因是类型擦除.泛型没有存储在类中,它们只是编译时信息,因此在运行时,这两种方法是相同的,因此存在命名冲突.

The reason is type erasure. Generics are not stored in the classes, they are compile-time info only, so at runtime, the two methods are identical and hence there is a naming conflict.

参考

这三种方法实际上是相同的(阅读:它们产生相同的字节码):

These three methods are actually identical (read: they produce identical bytecode):

public static void a(Set plainSet) {}
public static void a(Set<String> stringSet) {}
public static void a(Set<Map<String,String>> mapSet) {}

如果您确实想拥有两个单独的方法,则必须提供不同的方法签名(例如,不同的方法名称,其中一个方法的附加参数等)

If you really want to have two separate methods, you must provide different method signatures (e.g. different method names, an additional parameter for one of the methods etc.)

这篇关于泛型方法重载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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