How to call / execute a method programmatically in android

Calling a method without return value

/**
 * @param className Full name of the class in which this method is defined <br/>
 * @param classObject class object in which this method is defined <br/>
 * @param methodName name of the method whcih you want to execute <br/>
 * @param methodParamerters parameters of the method. Pass <b>null</b> if this method has no parameters <br/> <br/>

 @see
 <code>
 package com.sample.passingmethod; <br/><br/>

import android.app.Activity; <br/>
 import android.os.Bundle;<br/><br/>

public class SampleClass extends Activity <br/>
 {<br/><br/>

 public void onCreate(Bundle savedInstanceState) <br/>
 {<br/>
 super.onCreate(savedInstanceState);<br/>
 setContentView(R.layout.main);<br/><br/>

 String className = "com.hb.passingmethod.SampleClass";<br/>
 SampleClass obj = new SampleClass();<br/>
 String myMethod = "display";<br/>
 <br/>
 Object parameters[] = {"hi"};<br/>
 <br/>
 executeMethod(className,obj,myMethod,parameters);<br/>
 }<br/>
 <br/>
 public void display(String text)<br/>
 {<br/>
 Toast.makeText(this, ""+text, Toast.LENGTH_SHORT).show();<br/>
 }<br/>

 public void add(Integer i,Integer j)<br/>// this is method is not executed if you pass <b>int i, int j</b><br/>
 {<br/>
 Toast.makeText(this, "Sum of "+i+" and "+j+" is "+(i+j), Toast.LENGTH_SHORT).show();<br/>
 }<br/>

 }<br/>
 </code><br/>

 * <b>Note:</b> The method which you want to execute should be declared as <b>public</b> <br/>
 * If you are passing <b>Wrapper class</b> value as parameter then you must pass it as an <b>object</b> of that class<br/>
 * <br/><b>For eg:</b> If you want to pass <b>int i</b> then pass as <b>Integer i</b> or <b>new Integer(i)</b>. Otherwise, it will raise <b>NoSuchMethodFound Exception</b>
 * In the similar way you have to pass for <b>boolean,byte,char,short,int,long,float and double</b> data types.
 */
 public static void executeMethod(String className, Object classObject, String methodName, Object[] methodParamerters)
 {
 try
 {
 Class<?> myclass = Class.forName(className);

 Class<?> parameterTypes[] = null;

 if(methodParamerters!=null)
 {
 parameterTypes = new Class[methodParamerters.length];

 for (int i = 0; i < methodParamerters.length; i++)
 {
 className = methodParamerters[i].getClass().getName();
 parameterTypes[i] = Class.forName(className);
 }
 }

 Method method = myclass.getMethod(methodName, parameterTypes);
 method.invoke(classObject, methodParamerters);
 }
 catch (Exception e)
 {
 e.printStackTrace();
 }

 }

Calling a method with return value

/**
 * @param className Full name of the class in which this method is defined <br/>
 * @param classObject class object in which this method is defined <br/>
 * @param methodName name of the method whcih you want to execute <br/>
 * @param methodParamerters parameters of the method. Pass <b>null</b> if this method has no parameters <br/> <br/>

 @see
 <code>
 package com.sample.passingmethod; <br/><br/>

import android.app.Activity; <br/>
 import android.os.Bundle;<br/><br/>

public class SampleClass extends Activity <br/>
 {<br/><br/>

 public void onCreate(Bundle savedInstanceState) <br/>
 {<br/>
 super.onCreate(savedInstanceState);<br/>
 setContentView(R.layout.main);<br/><br/>

 String className = "com.hb.passingmethod.SampleClass";<br/>
 SampleClass obj = new SampleClass();<br/>
 String myMethod = "display";<br/>
 <br/>
 Object parameters[] = {"hi"};<br/>
 <br/>
 executeMethod(className,obj,myMethod,parameters);<br/>
 }<br/>
 <br/>

public void add(Integer i,Integer j)<br/>// this is method is not executed if you pass <b>int i, int j</b><br/>
 {<br/>
 Toast.makeText(this, "Sum of "+i+" and "+j+" is "+(i+j), Toast.LENGTH_SHORT).show();<br/>
 }<br/>

 }<br/>
 </code><br/>

 * <b>Note:</b> The method which you want to execute should be declared as <b>public</b> <br/>
 * If you are passing <b>Wrapper class</b> value as parameter then you must pass it as an <b>object</b> of that class<br/>
 * <br/><b>For eg:</b> If you want to pass <b>int i</b> then pass as <b>Integer i</b> or <b>new Integer(i)</b>. Otherwise, it will raise <b>NoSuchMethodFound Exception</b>
 * In the similar way you have to pass for <b>boolean,byte,char,short,int,long,float and double</b> data types.
 */
 public static Object executeMethodAndGetReturnValue(String className, Object classObject, String methodName, Object[] methodParamerters)
 {
 Object returnValue=null;
 try
 {
 Class<?> myclass = Class.forName(className);

 Class<?> parameterTypes[] = null;

 if(methodParamerters!=null)
 {
 parameterTypes = new Class[methodParamerters.length];

 for (int i = 0; i < methodParamerters.length; i++)
 {
 className = methodParamerters[i].getClass().getName();
 parameterTypes[i] = Class.forName(className);
 }
 }

 Method method = myclass.getMethod(methodName, parameterTypes);
 returnValue = method.invoke(classObject, methodParamerters);
 }
 catch (Exception e)
 {
 e.printStackTrace();
 }

 return returnValue;
 }
Advertisements

Tags: ,

About krishjlk

http://www.facebook.com/krishna.kanth.121

One response to “How to call / execute a method programmatically in android”

  1. A.Ramesh says :

    Nice stuff ! Reflection has great power in java. Especially we use this when methods or classes are not available to other classes. For instance in android ActivityManagerNative is not available to other class, still we want to use this class and execute methods in this class. In this case we use this method. (This is working in api level14 if u want to check this).

    private static Object am = null;
    private static Method getConfigurationMethod;
    private static Method updateConfigurationMethod = null;

    Class mActiveManagerNative = Class
    .forName(“android.app.ActivityManagerNative”);

    Class localClass2 = Class.forName(“android.app.IActivityManager”);
    android.app.ActivityManager l;

    Object localObject = mActiveManagerNative.getMethod(“getDefault”,
    null).invoke(mActiveManagerNative, null);
    am = localClass2.cast(localObject);

    getConfigurationMethod = am.getClass().getMethod(
    “getConfiguration”, null);

    Class[] arrayOfClass = new Class[1];
    arrayOfClass[0] = Configuration.class;
    updateConfigurationMethod = am.getClass().getMethod(
    “updatePersistentConfiguration”, arrayOfClass);

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: