java 反射

王朝学院·作者佚名  2016-05-28
窄屏简体版  字體: 小  |  中  |  大  |  超大  

java 反射package com.reflect;import java.lang.reflect.Method;public class ReflectUitl { public static Method getMethodDemo(Class clazz, String methodName, final Class[] classes) { Method method = null; // methodName 方法名称, classes 方法类型参数数据 try { method = clazz.getDeclaredMethod(methodName, classes); } catch (NoSuchMethodException e) { try { clazz.getMethod(methodName, classes); } catch (NoSuchMethodException e1) { if (clazz.getSuperclass() == null) { return method; } else { method = getMethodDemo(clazz.getSuperclass(), methodName, classes); } } } return method; } public static Object invoke(Object obj, String methodname, Class[] classes, Object[] object) { Method method = getMethodDemo(obj.getClass(), methodname, classes); method.setaccessible(true); Object inObj = null; try { inObj = method.invoke(obj, object); } catch (Exception e) { System.out.PRintln(e.getMessage()); } return inObj; } public static Object invoke(final Object obj, final String methodName) { return invoke(obj, methodName, new Class[] {}, new Object[] {}); } public static Object invoke(final Object obj, final String methodName, final Class[] classes) { return invoke(obj, methodName, classes, new Object[] {}); } public static void main(String[] args) throws Exception { ReflectUitl.invoke(new Demo2(), "printlnB"); }

// demo2 类, 自行定义。}

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航