反射获取成员方法并运行

﹏ヽ暗。殇╰゛Y 2023-01-18 06:45 202阅读 0赞
  1. /*
  2. * 反射获取成员防范并运行
  3. * public void eat() {}
  4. */
  5. public class ReflectDemo6 {
  6. public static void main(String[] args) throws Exception {
  7. Class c = Class.forName("cn.itcasat.demo1.Person");
  8. Object obj = c.newInstance();
  9. // 获取class对象中的成员方法
  10. // Method[] getMethods()获取的是class文件中的所有公共成员方法,包括继承的
  11. // Method类是描述成员方法的对象
  12. /* Method[] methods = c.getMethods();
  13. for (Method m : methods) {
  14. System.out.println(m);
  15. }*/
  16. //获取指定的方法eat运行
  17. //Method getMethod(String methodName, Class...c)
  18. //methodName获取的方法名 c 方法的参数列表
  19. Method method = c.getMethod("eat");
  20. //使用Method类中的方法,运行获取到的方法eat
  21. // Object invoke(Object obj, Object...o)
  22. method.invoke(obj);
  23. }
  24. }

发表评论

表情:
评论列表 (有 0 条评论,202人围观)

还没有评论,来说两句吧...

相关阅读