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

    反射:获得某个对象的类对象,进行反射获取该对象的方法、属性、注解、构造器等
     

    反射获得class类的四种方法:
    一、通过实例化的对象直接获得类对象:student1.getclass()
    二、通过forname方法获得:forName("com.Xan.test01.Student")
    三、知道所需对象的名字直接获取:Student.class()
    四、获取实例化类的父类类对象:Student.getSuperclass()


    类的加载分为三步骤:
    一、加载:将class文件字节码内容加载到内存中
    二、链接:将java类的二进制代码合并到JVM的运行状态中
    三、初始化:执行类的构造器<clinit>()的过程。自动收集所有变量的赋值操作和static代码块的语句合并生成。

    获取Class对象的类命

    c1.getName()
    c1.getSimpleName()


     获取Class对象的类方法

    c1.getMethods()


     获取Class对象的属性

    c1.getFields()
    c1.getDeclaredFields()


     获取Class对象的构造器

    c1.getDeclaredConstructors();


     获取Class对象的特定方法

    c1.getDeclaredMethod("setName", String.class);


     获取Class对象的特定属性

    c1.getDeclaredField("name")





    会获取Class对象之后进行反射获取对象、方法、属性

     

    反射一个新的对象

    Person person = (Person)c1.newInstance(String.class)

     反射一个新的对象的方法

    Method setname = c1.getDeclaredMethod("setName",String.class)
    setname.invoke(person,"Xan");
    System.out.println(person.getName()); //OUTPUT::Xan

     反射一个新的对象的属性

    Field name = c1.getDeclaredField("name");
    name.setAccessible(true); //用于访问非公用
    name.set(person02,"XXXXAN");
    System.out.println(person02.getName());

    反射获取注解

    Class c1 = Class.forName("com.Xan.reflection.Student1");
    //反射获得注解
    Annotation[] annotations = c1.getAnnotations();
    for (Annotation annotation : annotations) {
    System.out.println(annotation);
    }
    
    //OUTPUT: @com.Xan.reflection.TableXan(value="db_student")
    
    //反射获得注解的value
    TableXan tableXan =(TableXan) c1.getAnnotation(TableXan.class);
    String value = tableXan.value();
    System.out.println(value);
    
    //OUTPUT: db_student
    
    //反射获得特定的注解
    Field f = c1.getDeclaredField("name");
    FieldXan annotation = f.getAnnotation(FieldXan.class);
    System.out.println(annotation.columnName());
    System.out.println(annotation.length());
    System.out.println(annotation.Type());
    
    
    //OUTPUT:
    db_varchar
    3
    int
  • 相关阅读:
    一维数组
    do while循环(熟悉)
    while循环的概念和使用
    break关键字
    continue关键字
    for循环的概念与使用
    switchcase分支结构
    if else if else分支结构
    关于scanf()读取与返回值和回车键的问题
    WCF通过IIS寄宿服务
  • 原文地址:https://www.cnblogs.com/richxan/p/12666807.html
Copyright © 2011-2022 走看看