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 then getMethod(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.

Byron Kiourtzoglou

Byron is a master software engineer working in the IT and Telecom domains. He is an applications developer in a wide variety of applications/services. He is currently acting as the team leader and technical architect for a proprietary service creation and integration platform for both the IT and Telecom industries in addition to a in-house big data real-time analytics solution. He is always fascinated by SOA, middleware services and mobile development. Byron is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button