Java Reflection - Methods

Jakob Jenkov
Last update: 2014-05-21

Using Java Reflection you can inspect the methods of classes and invoke them at runtime. This is done via the Java class java.lang.reflect.Method. This text will get into more detail about the Java Method object.

Obtaining Method Objects

The Method class is obtained from the Class object. Here is an example:

Class aClass = ...//obtain class object
Method[] methods = aClass.getMethods();

The Method[] array will have one Method instance for each public method declared in the class.

If you know the precise parameter types of the method you want to access, you can do so rather than obtain the array all methods. This example returns the public method named "doSomething", in the given class which takes a String as parameter:

Class  aClass = ...//obtain class object
Method method =
    aClass.getMethod("doSomething", new Class[]{String.class});

If no method matches the given method name and arguments, in this case String.class, a NoSuchMethodException is thrown.

If the method you are trying to access takes no parameters, pass null as the parameter type array, like this:

Class  aClass = ...//obtain class object
Method method =
    aClass.getMethod("doSomething", null);

Method Parameters and Return Types

You can read what parameters a given method takes like this:

Method method = ... // obtain method - see above
Class[] parameterTypes = method.getParameterTypes();

You can access the return type of a method like this:

Method method = ... // obtain method - see above
Class returnType = method.getReturnType();

Invoking Methods using Method Object

You can invoke a method like this:

//get method that takes a String as argument
Method method = MyObject.class.getMethod("doSomething", String.class);

Object returnValue = method.invoke(null, "parameter-value1");

The null parameter is the object you want to invoke the method on. If the method is static you supply null instead of an object instance. In this example, if doSomething(String.class) is not static, you need to supply a valid MyObject instance instead of null;

The Method.invoke(Object target, Object ... parameters) method takes an optional amount of parameters, but you must supply exactly one parameter per argument in the method you are invoking. In this case it was a method taking a String, so one String must be supplied.

Jakob Jenkov

Featured Videos

Java ConcurrentMap + ConcurrentHashMap

Java Generics

Java ForkJoinPool

P2P Networks Introduction

















Close TOC
All Tutorial Trails
All Trails
Table of contents (TOC) for this tutorial trail
Trail TOC
Table of contents (TOC) for this tutorial
Page TOC
Previous tutorial in this tutorial trail
Previous
Next tutorial in this tutorial trail
Next