Java通过反射实现实例化
2013-08-25 20:42
411 查看
public static void main(String[] args) throws Exception { User user= (User) test(User.class); System.out.println(user.getMoney()); invokeTest(user,"getMoneyT"); } /**通过反射获取实例 * @param clazz类,如user.class * @return 类实例 * @throws Exception */ static Object test(Class clazz) throws Exception{ //clazz.newInstance();//实例化一个类,前提是该类存在无参构造参数 Constructor constructor=clazz.getConstructor(String.class);//得到构造器,String.class是即将实例化类clazz的构造参数的类型 Object obj= constructor.newInstance("test");//传入一个参数进行实例化 return obj; } /**调用指定方法 * @param obj对象 * @param methodName要调用的方法名 * @throws Exception */ static void invokeTest(Object obj,String methodName) throws Exception{ Method[] ms= obj.getClass().getDeclaredMethods();//当前类的方法,包括私有 //ms=obj.getClass().getMethods();//子类 父类的所有公共方法 for(Method m:ms){ System.out.println(m.getName()); if (m.getName().equals(methodName)) { m.invoke(obj, null);//调用无参方法 } } Method methods=obj.getClass().getMethod(methodName, null);//根据方法名和参数直接调用方法,方法无参传null methods.invoke(obj, null); } /**通过反射获取字段 * @param clazz * @throws Exception */ static void filed(Class clazz) throws Exception{ Field[] fs=clazz.getDeclaredFields();//当前类的字段,包括私有 //fs=clazz.getFields();//所有公共字段 for (Field field : fs) { System.out.println(field.getName()); } }
相关文章推荐
- 通过java反射实现静态变量替换
- 番外 01:Spring IoC 实现原理简析,Java的反射机制,通过类名创建对象
- java通过暴力反射创建不可实例化类的对象实例
- java反射获取实体类的属性名和值通过POI导出EXCEl,并实现表格列宽度自适应
- 番外 01:Spring IoC 实现原理简析,Java的反射机制,通过类名创建对象
- 如何理解java中的依赖注入 通过构造函数和反射机制来实现的
- Java反射02 : Class对象获取的三种方式和通过反射实例化对象的两种方式
- 通过java反射技术获取泛型的真实类型并对其实例化
- 番外 01:Spring IoC 实现原理简析,Java的反射机制,通过类名创建对象
- Java通过反射实现方法调用
- C++ 实现通过类名来进行实例化(反射机制?)
- java如何通过反射取得泛型的实例化对象
- 番外 01:Spring IoC 实现原理简析,Java的反射机制,通过类名创建对象
- java中通过泛型和反射实现类拷贝
- 番外 01:Spring IoC 实现原理简析,Java的反射机制,通过类名创建对象
- 番外 01:Spring IoC 实现原理简析,Java的反射机制,通过类名创建对象
- 番外 01:Spring IoC 实现原理简析,Java的反射机制,通过类名创建对象
- java通过反射,只需要传了类名和参数,就可以根据不同参数的构造方法实例化对象
- java通过反射实现HttpServlet
- 通过Java的反射机制实现对象的拷贝