Search This Blog

Friday, November 16, 2018

Java Dynamic Method Call with params by using reflection

package com.product.rpa.api.ws;

import java.lang.reflect.Method;

public class DynamicMethodCall
{
public String sample ()
{
return "vijay";
}

public String sampleWithParam ( String x )
{
return x + " " + x;
}

public String sampleWithMultipleParams ( String x, int i )
{
return x + " " + i;
}

public static void main ( String args[] ) throws Exception
{
DynamicMethodCall dynamicMethodCall = new DynamicMethodCall ();

// with out param
Method method = dynamicMethodCall.getClass ().getMethod ( "sample" );
String result = (String) method.invoke ( dynamicMethodCall );
System.out.println ( result );

// with param
// String parameter
Class [] paramString = new Class[1];
paramString[0] = String.class;

method = dynamicMethodCall.getClass ().getMethod ( "sampleWithParam", paramString );
result = (String) method.invoke ( dynamicMethodCall, "hi - param" );
System.out.println ( result );

// with multiple params
// String parameter
paramString = new Class[2];
paramString[0] = String.class;
paramString[1] = Integer.TYPE;

method = dynamicMethodCall.getClass ().getMethod ( "sampleWithMultipleParams", paramString );
result = (String) method.invoke ( dynamicMethodCall, "hi - ", 100 );
System.out.println ( result );

}
}

Post a Comment

Hit Counter


View My Stats