Java Reference
In-Depth Information
Let's look at the source code from
Method
to see what information and metadata is
held for each method:
private
Class
<?>
clazz
;
private
int
slot
;
// This is guaranteed to be interned by the VM in the 1.4
// reflection implementation
private
String
name
;
private
Class
<?>
returnType
;
private
Class
<?>[]
parameterTypes
;
private
Class
<?>[]
exceptionTypes
;
private
int
modifiers
;
// Generics and annotations support
private
transient
String
signature
;
// Generic info repository; lazily initialized
private
transient
MethodRepository
genericInfo
;
private
byte
[]
annotations
;
private
byte
[]
parameterAnnotations
;
private
byte
[]
annotationDefault
;
private
volatile
MethodAccessor
methodAccessor
;
This provides all available information, including the exceptions the method can
throw, annotations (with a retention policy of
RUNTIME
), and even the generics
information that was otherwise removed by
javac
.
We can explore the metadata contained on the
Method
object, by calling accessor
methods, but by far the single biggest use case for
Method
is reflexive invocation.
The methods represented by these objects can be executed by reflection using the
invoke()
method on
Method
. An example of invoking
hashCode()
on a
String
object follows:
Object
rcvr
=
"a"
;
try
{
Class
<?>[]
argTypes
=
new
Class
[]
{
};
Object
[]
args
=
null
;
Method
meth
=
rcvr
.
getClass
().
getMethod
(
"hashCode"
,
argTypes
);
Object
ret
=
meth
.
invoke
(
rcvr
,
args
);
System
.
out
.
println
(
ret
);
}
catch
(
IllegalArgumentException
|
NoSuchMethodException
|
SecurityException
e
)
{
e
.
printStackTrace
();
}
catch
(
IllegalAccessException
|
InvocationTargetException
x
)
{
x
.
printStackTrace
();
}
To get the
Method
object we want to use, we call
getMethod()
on the class object.
This will return a reference to a
Method
corresponding to a public method on the
class.