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