通用接口阵列 [英] Array of Generic Interface

查看:122
本文介绍了通用接口阵列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 接口示例< T> {} 

我们可以在java中创建一个通用接口数组吗? code>

在其他课程中

 样品LT; T> s [] = new Sample [2]; //为此,它显示警告

示例< T> s [] = new Sample< T> [2]; //为此,它显示错误


解决方案

不幸的是,Java不支持创建通用数组。我不知道确切的原因。实际上泛型只在编译时才存在,当你运行javac时,即从.java移动到.class时,它将被删除。但仅仅理解这个限制是不够的。可能他们有这种功能的一些向后兼容性问题。



以下是您可以使用的解决方法。


  1. 使用集合(例如列表)而不是数组。

     列表< Sameple> list = new ArrayList< Sameple>(); //这是好的,类型安全


  2. 创建没有泛型的数组,将代码放入特殊工厂方法用 @SuppressWarnings

    注释:
    $ b $ pre $ public class Test {
    接口示例< T> {}
    @SuppressWarnings(unchecked)
    public static< T>示例< T> [] sampleArray(){
    return new Sample [2];


    code $


    现在,您可以使用此工厂方法,而无需任何其他警告。

    一般提示。

    禁止警告是不好的做法。警告是潜在的问题。所以如果我必须抑制警告,我至少应该减少警告被抑制的范围。
    不幸的是,遗留的java API不支持泛型。我们经常在使用这些API时收到警告。我总是试图将这些用途本地化为特殊类或至少像 sampelArray()这样的方法。这些方法由 @SuppressWarning 标记,并且通常包含解释警告在此处被抑制的原因。

    Can we create array of generic interface in java?

    interface Sample<T>{}
    

    in other class

    Sample<T> s[] = new Sample[2] ; // for this it shows warning
    
    Sample<T> s[] = new Sample<T>[2];// for this it shows error
    

    解决方案

    Unfortunately Java does not support creation of generic arrays. I do not know the exact reason. Actually generics exist at compile time only and are removed when you run javac, i.e. move from .java to .class. But it is not enough to understand the limitation. Probably they had some backwards compatibility problems with such feature.

    Here are the workarounds you can use.

    1. Use collections (e.g. list) instead of array.

      List<Sameple> list = new ArrayList<Sameple>(); // this is OK and typesafe
      

    2. Create array without generics, put the code into special factory method annotated with @SuppressWarnings:

      public class Test {
          interface Sample<T>{}
          @SuppressWarnings("unchecked")
          public static <T> Sample<T>[] sampleArray() {
              return new Sample[2];
          }
      }
      

    Now you can use this factory method without any additional warning.

    General tip.

    It is bad practice to suppress warnings. Warnings are potential problems. So if I have to suppress warning I at least try to decrease the scope where the warning is suppressed. Unfortunately legacy java APIs do not support generics. We often get warnings when we use such APIs. I am always trying to localize such uses into special classes or at least methods like sampelArray(). These methods are marked by @SuppressWarning and often contain comment that explain why warnings are suppressed here.

    这篇关于通用接口阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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