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
Important Points regarding Varargs Before JDK 5, variable length arguments could be handled in two ways: One was using overloading, other was using array argument. There can be only one variable argument in a method. Variable argument (Varargs) must be the last argument.
Varargs is a short name for variable arguments. In Java, an argument of a method can accept arbitrary number of values. This argument that can accept variable number of values is called varargs. The syntax for implementing varargs is as follows: accessModifier methodName(datatype… arg) { // method body }
Generally speaking, you should not overload a varargs method, or it will be difficult for programmers to figure out which overloading gets called. "
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With