reflection
Invoke Method with reflection
With this example we are going to demonstrate how to invoke a method using reflection. In short, to invoke a method using reflection you should:
- Create a new StringBuilder with no characters in it and an initial capacity of 16 characters.
- Append a specified String to the builder using
append(String str)
API method of StringBuilder. - Use
getClass()
API method to get the runtime class of the StringBuilder and thengetMethod(String name, Class<?>... parameterTypes)
API method of Class to get the Method object that reflects the specified public member method of the class or interface represented by this Class object. - Use
invoke(Object obj, Object... args)
API method to invoke the underlying method represented by this Method object, on the specified object with the specified parameters. Individual parameters are automatically unwrapped to match primitive formal parameters, and both primitive and reference parameters are subject to method invocation conversions as necessary.
Let’s take a look at the code snippet that follows:
package com.javacodegeeks.snippets.core; import java.lang.reflect.Method; public class InvokeMethodWithReflection { public static void main(String[] args) throws Exception { StringBuilder sb = new StringBuilder(); sb.append("Java Code Geeks"); System.out.println("Initial: " + sb); // retrieve the method named "append" Method appendMethod = sb.getClass().getMethod("append", String.class); // invoke the method with the specified argument appendMethod.invoke(sb, "Java Examples & Code Snippets"); System.out.println("Final: " + sb); } }
Output:
Initial: Java Code Geeks
Final: Java Code GeeksJava Examples & Code Snippets
This was an example of how to invoke a method using reflection in Java.