Java Reference
In-Depth Information
Note I'vespecified catch (Exception e) toavoidhavingtospecifymultiple
catch blocks. You could also use multicatch (see Chapter 3 ) where appropriate.
Method representsamethodanddeclaresvariousmethods,includingthefollowing
methods:
int getModifiers() returnsa32-bitintegerwhosebitfieldsidentifythe
method'sreservedwordmodifiers(suchas public , abstract ,or static ).
Thesebitfieldsmustbeinterpretedviathe Modifier class.Forexample,you
might specify (method.getModifiers()&Modifier.ABSTRACT)
== Modifier.ABSTRACT to find out if the method (represented by the
Method objectwhosereferenceisstoredin method )isabstract—thisexpres-
sion evaluates to true when the method is abstract.
Class<?> getReturnType() returnsa Class objectthatrepresentsthe
method's return type.
Object invoke(Object receiver, Object... args) callsthe
method on the object identified by receiver (which is ignored when the
methodisaclassmethod),passingthevariablenumberofargumentsidentified
by args tothecalledmethod.The invoke() methodthrows NullPoint-
erException when receiver is null andthemethodbeingcalledisan
instance method, IllegalAccessException when the method is not ac-
cessible (it is private, for example), IllegalArgumentException when
anincorrectnumberofargumentsarepassedtothemethod(andotherreasons),
and InvocationTargetException when an exception is thrown from
the called method.
boolean isVarArgs() returnstruewhenthemethodisdeclaredtoreceive
a variable number of arguments.
Listing 4-15 demonstrates Method 's invoke(Object, Object...) method.
Listing 4-15. Reflectively invoking instance and class methods
import java.lang.reflect.Method;
class X
{
public void objectMethod(String arg)
{
System.out.println("Instance method: "+arg);
Search WWH ::




Custom Search