Java Reflection - Methods

Language/JAVA 2014. 12. 1. 11:40

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 Stringas 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, aNoSuchMethodException 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 validMyObject 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.


출처 - http://tutorials.jenkov.com/java-reflection/methods.html


'Language > JAVA' 카테고리의 다른 글

Java Reflection - Private Fields and Methods  (0) 2014.12.01
Java Reflection - Getters and Setters  (0) 2014.12.01
Java Reflection - Fields  (0) 2014.12.01
Java Reflection - Constructors  (0) 2014.12.01
Java Reflection - Classes  (0) 2014.12.01
: