• Java基础:反射小结


    1 反射使java中的所有访问权限控制失去了作用!

    通过反射,我们能访问任何类的任何成员(包括成员变量和成员方法),能修改任何类的任何成员变量(final变量除外),也能执行任何类的成员方法。

    2 反射中Class类对象的创建方式

    在使用反射的过程中,我们往往要创建某个类型的Class类的对象,有3种方法。
    假设我们要创建一个 java.util.ArrayList 类型的Class类的对象。

    详见如下代码:

    public class Test1 {
        public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
    
            // 反射中Class类对象的创建方式1
            //   注意:需要强制类型转换
            Class<ArrayList> c = (Class<ArrayList>) Class.forName("java.util.ArrayList");
            // 反射中Class类对象的创建方式2
            //   注意:不用强制类型转换
            c = ArrayList.class;
            // 反射中Class类对象的创建方式3
            //   注意:需要强制类型转换
            ArrayList arrayList = new ArrayList();
            c = (Class<ArrayList>) arrayList.getClass();
            // 通过ArrayList类型的Class类对象获取ArrayList类对象的方法
            //   注意:不用强制类型转换
            arrayList = c.newInstance();
        }
    }
    

    3 Class类中的 getMethod() 和 getDeclaredMethod()的区别

    注:这一点参考了:https://www.cnblogs.com/williamcai/p/7110433.html
    Method getDeclaredMethod(String name, Class… parameterTypes)
    返回一个 Method 对象,该对象反映此 Class 对象所表示的类或接口的指定已声明方法。
    Method[] getDeclaredMethods()
    返回 Method 对象的一个数组,这些对象反映此 Class 对象表示的类或接口声明的所有方法,包括公共、保护、默认(包)访问和私有方法,但不包括继承的方法。
    Method getMethod(String name, Class… parameterTypes)
    返回一个 Method 对象,它反映此 Class 对象所表示的类或接口的指定公共成员方法。
    Method[] getMethods()
    返回一个包含某些 Method 对象的数组,这些对象反映此 Class 对象所表示的类或接口(包括那些由该类或接口声明的以及从超类和超接口继承的那些的类或接口)的公共 member 方法。
    getDeclaredField(String name)
    返回一个 Field 对象,该对象反映此 Class 对象所表示的类或接口的指定已声明字段。
    Field[] getDeclaredFields()
    返回 Field 对象的一个数组,这些对象反映此 Class 对象所表示的类或接口所声明的所有字段,包括公共、保护、默认(包)访问和私有字段,但不包括继承的字段。

  • 相关阅读:
    机器学习框架之sklearn简介
    ubuntu 16.04下使用 python pip的安装问题。
    ubuntu 16.04 搭建git小型服务器
    使用config 来管理ssh的会话
    【linux】su、sudo、sudo su、sudo -i的用法和区别
    【python】确保文件写入结束
    【python】描述符descriptor
    【python】类(资料+疑惑)
    【pymongo】mongodb cursor id not valid error
    【python】继承关系和isinstance
  • 原文地址:https://www.cnblogs.com/mediocreWorld/p/16033382.html
Copyright © 2020-2023  润新知