2009-05-21 114 views
11

我發佈a question last night關於Java反射,我發現編譯器警告今天上午。檢查Java反射調用的正確方法?

C:\javasandbox\reflection>javac ReflectionTest.java 
Note: ReflectionTest.java uses unchecked or unsafe operations. 
Note: Recompile with -Xlint:unchecked for details. 

C:\javasandbox\reflection>javac -Xlint:unchecked ReflectionTest.java 
ReflectionTest.java:17: warning: [unchecked] unchecked call to 
getDeclaredMethod(java.lang.String,java.lang.Class<?>...) as a member of the raw 
type java.lang.Class 

     myMethod = myTarget.getDeclaredMethod("getValue"); 
              ^
ReflectionTest.java:22: warning: [unchecked] unchecked call to 
getDeclaredMethod(java.lang.String,java.lang.Class<?>...) as a member of the raw 
type java.lang.Class 

     myMethod = myTarget.getDeclaredMethod("setValue", params); 
              ^
2 warnings 

是否有「適當的」方式來檢查這些返回的方法? (即是否有擺脫這些警告的正確方法是什麼?)

的源代碼:

import java.lang.reflect.*; 

class Target { 
    String value; 

    public Target() { this.value = new String("."); } 
    public void setValue(String value) { this.value = value; } 
    public String getValue() { return this.value; } 
} 

class ReflectionTest { 
    public static void main(String args[]) { 
     try { 
      Class myTarget = Class.forName("Target"); 

      Method myMethod; 
      myMethod = myTarget.getDeclaredMethod("getValue"); 
      System.out.println("Method Name: " + myMethod.toString()); 

      Class params[] = new Class[1]; 
      params[0] = String.class; 
      myMethod = myTarget.getDeclaredMethod("setValue", params); 
      System.out.println("Method Name: " + myMethod.toString()); 

     } catch (Exception e) { 
      System.out.println("ERROR"); 
     } 
    } 
} 

回答

33

變化

Class myTarget = Class.forName("Target"); 

Class<?> myTarget = Class.forName("Target"); 

這基本上意味着,「我知道它是通用的,但我對類型參數一無所知。「它們在語義上是等價的,但編譯器可以區分它們。有關更多信息,請參閱relevant Java Generics FAQ entry(「無界通配符實例與原始類型之間有什麼區別?」)。

+1

我相信當前的JDK7編譯器會在該行上提供rawtypes警告,以及使用變量的延遲未檢查警告。 – 2009-05-21 12:55:24