3

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.

user2125844
  • 315
  • 2
  • 3
  • 11
  • Are you sure they aren't just warnings? Use read over http://stackoverflow.com/questions/1205995/what-is-the-list-of-valid-suppresswarnings-warning-names-in-java and see if you can get them to stop. – flaviut Dec 01 '13 at 01:48
  • use @SuppressWarnings annotation for your class. Refer this. http://docs.oracle.com/javase/7/docs/api/java/lang/SuppressWarnings.html – Aditya Peshave Dec 01 '13 at 01:49

2 Answers2

6

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 ?
    ...
  } 
Vineet Kosaraju
  • 5,572
  • 2
  • 19
  • 21
2
Note: Recompile with -Xlint:unchecked for details.

javac -Xlint:unchecked filename.java

it will show the unchecked all exceptions that must catch through the user define or system define exception code

Akib Bagwan
  • 138
  • 1
  • 2
  • 14
  • That helped, thank you. My issue was an unchecked initialisation `HashMap returnMap = new HashMap(); ^ required: HashMap found: HashMap` – Rafs Mar 01 '23 at 10:11