泛型的静态方法重载 [英] Static Method Overloading with Generics

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

问题描述

在我尝试创建两个静态重载方法的地方,我收到了一个编译错误。任何人都可以解释这个

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


解决方案

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



参考





这三种方法实际上是相同的字节码):

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

如果你真的想要两个独立的方法,你必须提供不同的方法签名(例如不同的方法名称,一个方法的附加参数等)。

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.

Reference

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天全站免登陆