reflect
Posted 牧 天
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了reflect相关的知识,希望对你有一定的参考价值。
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(); } } }
以上是关于reflect的主要内容,如果未能解决你的问题,请参考以下文章