代码之家  ›  专栏  ›  技术社区  ›  Nate

检查Java反射调用的正确方法?

  •  13
  • Nate  · 技术社区  · 17 年前

    我张贴 a question last night 关于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");
            }
        }
    }
    
    1 回复  |  直到 9 年前
        1
  •  47
  •   Jon Skeet    17 年前

    改变

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

    到

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

    这基本上意味着,“我知道它是泛型的,但我对类型参数一无所知。”它们在语义上是等价的,但编译器可以分辨出区别。有关更多信息,请参阅 relevant Java Generics FAQ entry (“无界通配符实例化和原始类型之间有什么区别?”)。