Java: invoking a method by name


import java.lang.reflect.*;
 
public class Foo {
	public void bar(int param){
		System.out.println(param);
	}	
 
	public static void main(String args[]){
		Object f = new Foo();
		try {
			Method m = f.getClass().getMethod("bar", int.class);
			m.invoke(f, 42);
		} catch (Exception e){
			System.err.println(e);	
		}
	}
 
}

$ java Foo
42

  1. Be careful with reflection! :)

  2. перачытаў ўвесь блог, даволі нядрэнна

Leave a Comment


NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">