Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Meaning of new Class[0] in Reflection API

I came across a statement:

o1 = o1.getClass().getMethod(getter, new Class[0]).invoke(o1, new Object[0]);

Can someone please tell me what new Class[0] and new Object[0] do in this case, where o1 is any Object?

like image 720
user2549538 Avatar asked Aug 08 '13 03:08

user2549538


2 Answers

getMethod() takes a list of types for arguments. Passing a zero-length array means it has no arguments. Same for invoke().

From the documentation for Class.getMethod:

If parameterTypes is null, it is treated as if it were an empty array.

From the documentation for Method.invoke:

If the number of formal parameters required by the underlying method is 0, the supplied args array may be of length 0 or null.

The line you posted, in that context, then, is equivalent to:

o1 = o1.getClass().getMethod(getter, null).invoke(o1, null);

Personally I find the use of null there to be more readable (although the use of a zero-length array does have the benefit of self-documenting the type of parameter that the programmer is not passing, if that means much to you).

like image 199
Jason C Avatar answered Oct 06 '22 01:10

Jason C


o1.getClass().getMethod(getter, new Class[0])

It means it tells Class#getMethod to find a method named getter which has NO arguments.

Its same as

o1.getClass().getMethod(getter, null)
like image 23
Jayamohan Avatar answered Oct 06 '22 01:10

Jayamohan