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

    1、反射获取Class对象的三种方式

    反编译
    不是自己写的类,也不知道类里面有哪些方法 变量,让你能够使用程序上线了,修改程序但不终止程序的运行—-反射
    (1)Object类 getClass 方法
    getClass 返回此Object的运行时类
    getName() 返回由 类对象表示的实体(类,接口,数组类,原始类型或空白)的名称,作为 String

    (2)通过Class属性获得
    都有一个静态的class属性

    (3)通过 forName
    static 类<?> forName(String className) 返回与给定字符串名称的类或接口相关联的 类对象

    2、反射获得构造方法

    (1)获得构造方法

    Constructor<T> getDeclaredConstructor(类<?>... parameterTypes)
    返回一个 Constructor对象,该对象反映 Constructor对象表示的类或接口的指定 类函数
    Constructor<?>[] getDeclaredConstructors()
    返回一个反映 Constructor对象表示的类声明的所有 Constructor对象的数组 类
    Constructor<T> getConstructor(类<?>... parameterTypes)
    返回一个 Constructor对象,该对象反映 Constructor对象表示的类的指定的公共类函数
    Constructor<?>[] getConstructors()
    返回包含一个数组 Constructor对象反射由此表示的类的所有公共构造 类对象

    (2)使用构造方法
    public T newInstance() throws InstantiationException, IllegalAccessException
    访问私有的构造方法。必须通过Accessible设置为true。强行访问

    public void setAccessible(boolean flag) throws SecurityException将此对象的accessible标志设置为指示的布尔值

    true的值表示反射对象应该在使用时抑制Java语言访问检查。 false的值表示反映的对象应该强制执行Java语言访问检查

    3、反射获得成员变量

    (1)获得字段
    Field[] getDeclaredFields()
    返回的数组 Field对象反映此表示的类或接口声明的所有字段 类对象

    getField(String name)
    返回一个 Field对象,它反映此表示的类或接口的指定公共成员字段 类对象

    Field[] getFields()
    返回包含一个数组 Field对象反射由此表示的类或接口的所有可访问的公共字段 类对象

    4、反射获得成员方法

    Declared–所有的
    Methods–公共的
    使用成员方法
    Object invoke(Object obj, Object… args)
    在具有指定参数的 方法对象上调用此 方法对象表示的底层方法

    5、泛型

    安全检测机制
    例如:

    ArrayList<T> arrylist=new ArrayList<T>();

    存在类型错误 类型无法转换成功

    6、泛型方法

    如何写一个方法 实现对 整数 浮点数 字符的输出。–泛型
    基本原则:

    a、所有泛型方法的声明都有一个类型参数声明的部分(<T>)--表示所有的类型参数
    b、泛型方法只能是引用数据类型,(int double

    例如:

    public static<T> void show(){
    }

    7、泛型类

    泛型类 增加了类型参数声明部分
    例如:

    class Test<T>
    {
    private T t;
    Test(T t){
    this.t=t;
    }
    }

    8、泛型擦除

    java本身不存在泛型。增加了泛型机制。—java虚拟机中都是确定的类型 泛型擦除

    9、类型通配符

    <?>–代替具体的类型参数
    例如:

    public void print(List<?> data){
    data.get(0);
    }
    <T>--指所有的数据类型

    10、反射与泛型

    泛型:允许程序员在编译时检测到非法的数据类型,运行期间Object,泛型擦除
    通过反射可以添加不同的数据类型

  • 相关阅读:
    ExecuteScalar requires the command to have a transaction when the connection assigned to the command is in a pending
    如何从vss中分离程序
    String or binary data would be truncated
    the pop3 service failed to retrieve authentication type and cannot continue
    The POP3 service failed to start because
    IIS Error he system cannot find the file specified _找不到页面
    pku2575Jolly Jumpers
    pku2940Wine Trading in Gergovia
    pku3219二项式系数
    pku1029false coin
  • 原文地址:https://www.cnblogs.com/hsiehchou/p/10403403.html
Copyright © 2011-2022 走看看