Java Reference
In-Depth Information
// To find a method we need the array of matching Class types.
Class
<?>[]
argTypes
= {
int
int
.
class
,
String
.
class
};
// Now find a Method object for the given method.
Method worker
=
clX
.
getMethod
(
"work"
,
argTypes
);
// To INVOKE the method, we need the invocation
// arguments, as an Object array.
Object
[]
theData
= {
42
,
"Chocolate Chips"
};
// The obvious last step: invoke the method.
// First arg is an instance, null if static method
worker
.
invoke
(
new
new
X
(),
theData
);
}
catch
catch
(
Exception e
) {
System
.
err
.
println
(
"Invoke() failed: "
+
e
);
}
}
}
Not tiny, but it's still not bad. In most programming languages, you couldn't do that in the 40
lines it took us here.
A word of caution: when the arguments to a method are of a primitive type, such as
int
, you
do not pass
Integer.class
into
getMethod()
. Instead, you must use the class object repres-
enting the primitive type
int
. The easiest way to find this class is in the
Integer
class, as a
public constant named
TYPE
, so you'd pass
Integer.TYPE
. The same is true for all the prim-
itive types; for each, the corresponding wrapper
class
has the primitive
class
referred to as
TYPE
.
Accessing Private Methods and Fields via Reflection
Problem
You want to access private fields and have heard you can do so using the Reflection API.