Skip to content

Tag: Class

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

Java: Accessing Private Members

Using reflection to change the accessibility of a private object field and access it at runtime.

import java.lang.reflect.Field;
 
class Life {
    private int meaning = 42;
}
 
class Hack {
    public static void main(String args[]){
        Life life = new Life();
        try {
            Field field = life.getClass().getDeclaredField("meaning");
            field.setAccessible(true);
            System.out.println(field.get(life));
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e){
            e.printStackTrace();
        }
    }
}

Output:

42