使用反射获取对象的步骤

  • 获取类的Class对象实例
Class clz = Class.forName("com.reflect.Apple");
  • 根据Class对象实例获取Constructor对象
Constructor appleConstructor = clz.getConstructor();
  • 使用 Constructor对象的newInstance方法获取反射对象
Object appleObj = appleConstructor.newInstance();

而如果要调用某一个方法,则需要经过下面的步骤:

  • 获取方法的Method对象
Method setPriceMethod = clz.getMethod("setPrice", int.class);
  • 利用 invoke 方法调用方法
setPriceMethod.invoke(appleObj, 14);

猜你喜欢

转载自www.cnblogs.com/Roni-i/p/10908351.html