Java – .java uses unchecked or unsafe operations. Note: Recompile with -Xlint:unchecked for details

javareflection

My teacher gave us some sample code to help to show how reflection in Java works however, I am getting some errors:

Note: DynamicMethodInvocation.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.

Here is the code:

import java.lang.reflect.*;
import java.lang.Class;
import static java.lang.System.out;
import static java.lang.System.err;

public class DynamicMethodInvocation {
  public void work(int i, String s) {
     out.printf("Called: i=%d, s=%s%n\n", i, s);
  }

  public static void main(String[] args) {
    DynamicMethodInvocation x = new DynamicMethodInvocation();

    Class clX = x.getClass();
    out.println("class of x: " + clX + '\n');

    // To find a method, need array of matching Class types.
    Class[] argTypes = { int.class, String.class };

    // Find a Method object for the given method.
    Method toInvoke = null;
    try {
      toInvoke = clX.getMethod("work", argTypes);
      out.println("method found: " + toInvoke + '\n');
    } catch (NoSuchMethodException e) {
      err.println(e);
    }

    // To invoke the method, need the invocation arguments, as an Object array
    Object[] theArgs = { 42, "Chocolate Chips" };

    // The last step: invoke the method.
    try {
      toInvoke.invoke(x, theArgs);
    } catch (IllegalAccessException e) {
      err.println(e);
    } catch (InvocationTargetException e) {
      err.println(e);
    }
  } 
}

I know nothing about reflection and if anyone knows how I can modify this code to get this to compile it would be very appreciated.

Best Answer

There is no compile error, this is just a warning. You can ignore this and the class will still work properly.

If you want to ignore these warnings, you can add the following above your method:

  @SuppressWarnings("unchecked")

Alternatively, you can fix this by changing the main method to:

public static void main(String[] args) {
    DynamicMethodInvocation x = new DynamicMethodInvocation();

    Class<?> clX = x.getClass(); // added the generic ?
    ...
  } 
Related Topic