java - 枚举警告

标签 java eclipse enumeration rxtx

我想用 Eclipse 执行 this RxTx web site 提供的示例代码 :

import gnu.io.*;
public class SerialPortLister {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        listPorts();
    }
    private static void listPorts()
    {
        java.util.Enumeration<CommPortIdentifier> portEnum = CommPortIdentifier.getPortIdentifiers();  // this line has the warning
        while ( portEnum.hasMoreElements() ) 
        {
            CommPortIdentifier portIdentifier = portEnum.nextElement();
            System.out.println(portIdentifier.getName()  +  " - " +  getPortTypeName(portIdentifier.getPortType()) );
        }        
    }
    private static String getPortTypeName ( int portType )
    {
        switch ( portType )
        {
            case CommPortIdentifier.PORT_I2C:
                return "I2C";
            case CommPortIdentifier.PORT_PARALLEL:
                return "Parallel";
            case CommPortIdentifier.PORT_RAW:
                return "Raw";
            case CommPortIdentifier.PORT_RS485:
                return "RS485";
            case CommPortIdentifier.PORT_SERIAL:
                return "Serial";
            default:
                return "unknown type";
        }
    }
}

第 13 行有一个警告:Type safety: The expression of type Enumeration needs unchecked conversion to conform to Enumeration<CommPortIdentifier>

这个警告是什么意思,如何解决?

最佳答案

详细阐述 Vladislav Bauer 的第二个要点,您可以像这样初始化 portEnum:

Enumeration<?> portEnum = CommPortIdentifier.getPortIdentifiers();

然后在 while 结构内部,您可以将每个元素转换为您需要的类型,在本例中为 CommPortIdentifier:

 CommPortIdentifier portIdentifier = (CommPortIdentifier) portEnum.nextElement();

转换每个元素将使警告消失。但是我们必须小心并确保 portEnum 始终包含我们期望的 CommPortIdentifier 类型的元素。

关于java - 枚举警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8133460/

相关文章:

java - 找不到 ObjectDB EntityManager

java - 在Java中使用枚举制作评分表,然后允许用户输入数字成绩以输出字母成绩

web-services - 使用 ColdFusion 的 .net Web 服务时出现问题

Java - 从字符串中获取名称

java - 在 Java Eclipse 中指定绝对路径时找不到文件

java - 如何避免使用 mongoDB Java 驱动程序 3.4+ 或 3.6+ 过早到达流末尾的异常? (插入时)

java - 如何使用 WindowBuilder 在内部类中编辑 JPanel

c++ - 在函数中使用枚举参数

java - 比较 2 128 以下的整数

java - 如何在 java 代码中读取 View 的 android 默认属性