zoukankan      html  css  js  c++  java
  • Java 反射机制

    主要补充反射集中比较深入的部分。

    getFields()获得某个类的所有的公共(public)的字段,包括父类。 
    getDeclaredFields()获得某个类的所有申明的字段,即包括public、private和proteced,但是不包括父类的申明字段。 
    同样类似的还有getConstructors()和getDeclaredConstructors(),getMethods()和getDeclaredMethods()。
     
    实例化类
     Class<?> class1 = null;
            class1 = Class.forName("net.xsoftlab.baike.User");
            User user = (User) class1.newInstance();
            user.setAge(20);
            user.setName("Rollen");
      
            Constructor<?> cons[] = class1.getConstructors();
            user = (User) cons[0].newInstance("Rollen");
            user = (User) cons[1].newInstance(20, "Rollen");

    直接调用类中的方法

           Class<?> clazz = Class.forName("net.xsoftlab.baike.TestReflect");
            // 调用TestReflect类中的reflect1方法
            Method method = clazz.getMethod("reflect1");
            method.invoke(clazz.newInstance());
     // 调用TestReflect的reflect2方法
            method = clazz.getMethod("reflect2", int.class, String.class);
            method.invoke(clazz.newInstance(), 20, "张三");

    关于数组的反射的应用

                 int [] inttt={1,2,3};
                System.out.println(inttt.getClass());//输出的是数组对象的Class
                //getComponentType是如果class是一个数组的对象,就返回的是数组对象中的元素的Class,否则返回null
                System.out.println(inttt.getClass().getComponentType());//输出int
                System.out.println(String.class.getComponentType());//输出null

    反射中数组的操作,一般要用到java.lang.reflect.Array的这个类,它里面提供了对于数组的一些静态方法,包括get、set、getlenth、newinstance等

         //扩充数组大小
    public
    static Object arrinc(Object obj,int len){ Class<?> arr=obj.getClass().getComponentType(); Object newArr=Array.newInstance(arr, len); int size=Array.getLength(obj); System.arraycopy(obj, 0, newArr, 0, size); return newArr; }
    //打印数组
    public static void arrprint(Object obj){ Class<?> cc=obj.getClass(); if(cc.isArray()){ int length=Array.getLength(obj); for(int i=0;i<length;i++){ System.out.print(Array.get(obj,i)); } System.out.println(); } }
     
     
  • 相关阅读:
    socketpair和pipe的区别
    C++异常与析构函数及构造函数
    System v shm的key
    不可靠信号SIGCHLD丢失的问题
    非阻塞IO函数
    Android 编译时出现r cannot be resolved to a variable
    找工作笔试面试那些事儿(5)---构造函数、析构函数和赋值函数
    unable to load default svn client 和 Eclipse SVN 插件与TortoiseSVN对应关系
    演示百度地图操作功能
    求第i个小的元素 时间复杂度O(n)
  • 原文地址:https://www.cnblogs.com/Coder-Pig/p/6673670.html
Copyright © 2011-2022 走看看