zoukankan      html  css  js  c++  java
  • java 反射

    反射的作用:

      1. 反编译:.class-->.java

      2. 在运行状态中,通过反射机制访问java对象的属性,方法,构造方法等;

    反射的实现

    //第一种方式:  
    Class c1 = Class.forName("Employee");  
    //第二种方式:  
    //java中每个类型都有class 属性.  
    Class c2 = Employee.class;  
       
    //第三种方式:  
    //java语言中任何一个java对象都有getClass 方法  
    Employeee = new Employee();  
    Class c3 = e.getClass(); //c3是运行时类 (e的运行时类是Employee)  

    带构造参数的类反射

    // 获得指定字符串类对象
            Class cl = Class.forName("com.test.User");
            //设置Class对象数组,用于指定构造方法类型  
            Class[] parameterTypes = new Class[] { String.class, int.class };
            
             //获得Constructor构造器对象。并指定构造方法类型  
            Constructor constructor = cl.getConstructor(parameterTypes);
              //给传入参数赋初值  
            Object[] parameter = { "lili", new Integer(15) };
              
            //得到实例 
            Object newInstance = constructor.newInstance(parameter);

     执行方法

            Class<?> class1 = Class.forName("com.test.User");
            
            Method method = class1.getMethod("getName");
            User newInstance = (User) class1.newInstance();
            newInstance.setName("crazy");
            // 执行方法,并返回方法的返回值
            Object result = method.invoke(newInstance);
            System.out.println("crazy:"+result);
  • 相关阅读:
    Halcon学习笔记之缺陷检测(二)
    tensorflow常用函数库
    luogu P2765 魔术球问题 (最小路径覆盖)
    luogu P2423 [HEOI2012]朋友圈 (最大团)
    poj 2226 Muddy Fields (二分图)
    匈牙利算法板子
    二分图
    AC日记——【模板】树链剖分 洛谷 P3384
    AC日记——[ZJOI2008]树的统计Count bzoj 1036
    去重排序
  • 原文地址:https://www.cnblogs.com/newlangwen/p/7197157.html
Copyright © 2011-2022 走看看