49

This is my sample code where i am getting the warning.

Class aClass = Class.forName(impl);
Method method = aClass.getMethod("getInstance", null);
item = (PreferenceItem) method.invoke(null, null);

The warning:

warning: non-varargs call of varargs method with inexact argument type for last parameter; cast to java.lang.Class for a varargs call cast to java.lang.Class[] for a non-varargs call and to suppress this warning Method method = aClass.getMethod("getInstance", null);

please help me solve this problem

Kariem
  • 4,398
  • 3
  • 44
  • 73
Mohsin
  • 609
  • 1
  • 7
  • 7

1 Answers1

79

Well, the compiler warning tells you everything you need to know. It doesn't know whether to treat null as a Class<?>[] to pass directly into getMethod, or as a single null entry in a new Class<?>[] array. I suspect you want the former behaviour, so cast the null to Class<?>[]:

Method method = aClass.getMethod("getInstance", (Class<?>[]) null);

If you wanted it to create a Class<?>[] with a single null element, you'd cast it to Class<?>:

Method method = aClass.getMethod("getInstance", (Class<?>) null);

Alternatively you could remove the argument altogether, and let the compiler build an empty array:

Method method = aClass.getMethod("getInstance");
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 1
    Thanks Jon that warning has been goon............ I have just change my code as you suggest aClass.getMethod("getInstance"); – Mohsin Mar 23 '11 at 06:52
  • If anyone was wondering (like me), it seems to default to treating the null as the whole array `Class>[]`, not a single null element inside an array (at least according to answers posted here: http://stackoverflow.com/questions/4028059/calling-java-varargs-method-with-single-null-argument). Of course, it's probably best practice to cast for specificity, but it's good to know when considering whether to refactor methods that take an Array as the last argument into varargs. – Vivek Chavda Jan 19 '17 at 22:18
  • 1
    Where in the JLS is the rationale for the fact that in this example a cast to `Class>` would produce an array with a single `null` element?. – Jaime Hablutzel May 13 '17 at 20:32
  • 1
    @JaimeHablutzel: Because `Class.getMethod(String, Class>)` doesn't exist - so the first two phases in 15.12.2 wouldn't find any method to call. With varargs, it works because there *is* a variable arity method `Class.getMethod(String, Class>[])` - see 15.12.2.4. The array is constructed as per 15.12.4.2, with the argument (value null) being the sole element in the array. – Jon Skeet May 14 '17 at 06:31