2011-11-15 53 views
1

我想用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>

是什麼警告的含義及如何解決呢?

+0

我想你還應該顯示getPortIdentifiers的代碼 – Bozho

+0

請在此處註明行號,在那裏插入註釋。 –

+0

getPortIdentifiers()是一個靜態方法 – pheromix

回答

0

我不知道getPortIdentifiers方法的代碼,但在目前的情況:

  • 的解決方案是增加以下標註在對其報道的警告前面的方法:@SuppressWarnings( 「unchecked」)

  • 您也可以將類型轉換爲未知類型。示例:Enumeration portEnum = CommPortIdentifier.getPortIdentifiers();

3

闡述更多的弗拉迪斯拉夫·鮑爾第二個小點,你可以初始化portEnum這樣的:

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

然後是同時結構的內部,你可以做的每個元素的鑄造類型你所需要的,在這種情況下CommPortIdentifier:

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

鑄造每個元素將使警告消失。但是我們必須小心並確保portEnum總是包含CommPortIdentifier類型的元素,正如我們所期望的那樣。

相關問題