Java Reference
In-Depth Information
main() next creates a one-element Class array that describes the types of ob-
jectMethod() 'sparameterlist.Thisarrayisusedinthesubsequentcallto Class 's
Method getMethod(String name, Class<?>... parameterTypes)
method to return a Method object for invoking a public method named ob-
jectMethod with this parameter list. This method throws
java.lang.NoSuchMethodException when the named method doesn't exist.
Continuing, main() createsan Object arraythatspecifiesthedatatobepassedto
themethod'sparameters;inthiscase,thearrayconsistsofasingle String argument.It
thenreflectivelyinvokes objectMethod() bypassingthisarrayalongwiththeob-
ject reference stored in x to the invoke() method.
At this point, main() shows you how to reflectively invoke a class method. The
(Class<?>[]) and (Object[]) castsareusedtosuppresswarningmessagesthat
havetodowithvariablenumbersofargumentsandnullreferences.Noticethatthefirst
argument passed to invoke() is null when invoking a class method.
The java.lang.reflect.AccessibleObject class is the superclass of
Constructor , Field ,and Method .Thissuperclassprovidesmethodsforreporting
aconstructor's,field's,ormethod'saccessibility(isitprivate?)andmakinganinaccess-
ibleconstructor,field,ormethodaccessible. AccessibleObject 'smethodsinclude
the following:
T getAnnotation(Class<T> annotationType) returns the con-
structor's,field's,ormethod'sannotationofthespecifiedtypewhensuchanan-
notation is present; otherwise, null returns.
boolean isAccessible() returns true when the constructor, field, or
method is accessible.
boolean isAnnotationPresent(Class<? extends Annota-
tion> annotationType) returnstruewhenanannotationofthetypespe-
cified by annotationType has been declared on the constructor, field, or
method. This method takes inherited annotations into account.
void setAccessible(boolean flag) attemptstomakeaninaccess-
ible constructor, field, or method accessible when flag is true .
Note The java.lang.reflect package also includes an Array class whose
class methods make it possible to reflectively create and access Java arrays.
I previously showed you how to obtain a Class object via Class 's forName()
method. Another way to obtain a Class object is to call Object 's getClass()
Search WWH ::




Custom Search