Enhancements in java.lang.Class and java.lang.reflect

The following methods in java.lang.Class were generified:

As a result, code which uses these methods now produces warnings during compilation.

For example, consider the following code which invokes getDeclaredMethod():

import java.lang.reflect.Method;

public class Warning {
    void m() {
        try {
            Warning warn = new Warning();
            Class c = warn.getClass();
            Method m = c.getDeclaredMethod("m");
        } catch (NoSuchMethodException x) {

$ javac Warning.java

Note: Warning.java uses unchecked or unsafe operations.

Note: Recompile with -Xlint:unchecked for details.

$ javac -Xlint:unchecked Warning.java

Warning.java:8: warning: [unchecked] unchecked call to getDeclaredMethod(java.lang.String,java.lang.Class<?>…) as a member of the raw type java.lang.Class            

Method m = c.getDeclaredMethod(“m”);                                          

^ 1 warning

  • To remove the warning, the declaration of c should be modified to include an appropriate generic type. In this case, the declaration should be:
    Class<?> c = warn.getClass();