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
?
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).
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)
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