Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I have got this warning: non-varargs call of varargs method with inexact argument type for last parameter;

Tags:

java

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

like image 218
Mohsin Avatar asked Mar 23 '11 06:03

Mohsin


People also ask

How do you handle varargs in Java?

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.

What is Varargs method in Java?

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 }

Is Varargs bad practice?

Generally speaking, you should not overload a varargs method, or it will be difficult for programmers to figure out which overloading gets called. "


1 Answers

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"); 
like image 106
Jon Skeet Avatar answered Oct 23 '22 00:10

Jon Skeet