package one; public class A { private int age; public A(int age) { this.age = age; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; public class B { public static void main(String[] args) { A a = new A(10); Class clazz = a.getClass(); try { System.out.println(a.getAge()); Method setMethod = clazz.getDeclaredMethod("setAge", new Class[] { int.class }); setMethod.invoke(a, new Object[] { Integer.valueOf(999) }); System.out.println(a.getAge()); Method getMethod = clazz.getDeclaredMethod("getAge", new Class[] {}); Integer age = (Integer) getMethod.invoke(a, new Object[] {}); System.out.println("---" + age.intValue()); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (SecurityException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } }