Home > Android > Call a function in android using string value(Using Java Reflection)

Call a function in android using string value(Using Java Reflection)

public void reflectionSample(String functionName){
		///this is used to call java methods using string value.		    
		Class c = MyClassName.class;
		///paraTypes: used to pass parameter to java function, its just a declaration.
		Class paraTypes[] = new Class[1];
		///the type of parameter is hash map.
		paraTypes[0] = HashMap.class;
		Method method = null;
		try {
			///class.getDeclaredMethod(java-function-name, java-function-parameter-type)
			///@param1: the string name of java function in class c
			///@param2: the type of parameter, like hashmap, string, int, etc
			method = c.getDeclaredMethod(functionName, paraTypes);
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		HashMap<String, String> argument = new HashMap<String, String>();
		argument.put("functionName", functionName);

		Object arg[] = new Object[1];
		arg[0] = new HashMap(argument);
		try {
			///method.invoke calls the java function
			method.invoke(this, arg);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void calledFromReflection(HashMap<String, String> text){
		System.out.println("---------------|"+text.get("functionName")+"|-------------");
	}


reflectionSample("calledFromReflection");

Learn about reflection
Reflection doc

Advertisements
Categories: Android Tags: ,
  1. No comments yet.
  1. No trackbacks yet.

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: