注解与反射学习总结

注解与反射

注解

注解(Annotation)概念:

  • 不是程序本身,可以对程序作出解释(这一点与注释(comment)没什么区别
  • 可以被其他程序(比如:编译器等)读取

注解的格式:

  • 注解是以”@注释名“在代码中存在的,还可以添加一些参数值,例如:

​ @SuppressWarnings(value=“unchecked”).

内置注解

package com.chen.annotation;

import java.lang.annotation.Documented;
import java.util.ArrayList;
import java.util.List;

//@SuppressWarnings  抑制警告信息
@SuppressWarnings("all")
public class Test01 extends Object{
    //@Override 重写的注解
    @Override
    public String toString() {
        return super.toString();
    }
    //@Deprecated 不推荐使用,里面的程序员是不鼓励的使用的,通常是危险的,或者存在更好的替代方法
    @Deprecated
    public static void test(){
        System.out.println("Deprecated");
    }
    public void test02(){
        List list = new ArrayList();
    }
    public static void main(String[] args) {
        test();
    }

}

元注解

作用:负责注解其他注解,用来提供对其他annotation类型作说明

package com.chen.annotation;

import java.lang.annotation.*;

//测试元注解
@MyAnnotation
public class Test02 {
    public void test(){
    }
}
//定义一个注解
//Target  表示我们的注解可以用在哪些地方
@Target(value = {ElementType.METHOD,ElementType.TYPE})

//Retention  表示注解在什么地方还有效
//runtime > class >sources
@Retention(value = RetentionPolicy.RUNTIME)

//Documented 表示是否将我们的注解生成在JAVAdoc中
@Documented

//Inherited 子类可以继承父类的注解
@Inherited
@interface MyAnnotation{
}

自定义注解

使用@interface自定义注解时,自动继承了java.lang.annotation.Annotation接口

格式:public @ interface 注解名{定义内容}

package com.chen.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

//自定义注解
public class Test03 {
    //注解可以显示赋值,如果没有默认值,就必须给注解赋值
    @MyAnnotation2(age = 18,name = "lc")
    public void test(){
    }
    @MyAnnotation3("lc")//直接赋值,不用写等式
    public void test2(){
    }
}
@Target({ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation2{
    //注解的参数:参数类型+参数名
    String name() default "";//加上default使用注解时可以不写,若不加,则必须声明
    int age() default 0;
    int id() default -1; //如果默认值为-1,代表不存在
    String[] schools() default {"zzu","励志学好编程"};
}
@Target({ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation3{
    String value();//如果定义的是value,且只有一个值,则可以省略  value= “ ”
}

反射机制

  • 动态语言:是一类在运行时可以改变其结构的语言;主要动态语言:c#,JavaScript,PHP,Python等;

  • 静态语言:运行时结构不可变的语言就是静态语言;如:Java、C、C++等;

  • Java不是动态语言,但是可以称之为"准动态语言"。即Java的反射(Reflection)机制可以获得类似动态语言的特性;

Class类

  • Class本身也是一个类
  • Class对象只能由系统建立对象
  • 一个加载的类在JVM中只会有一个Class实例
  • 一个Class对应对应的是一个加载到JVM中的一个.class文件
  • 每个类的实例都会记得 自己是由那歌Class实例所生成的
  • 通过Class可以完整的得到一个类中的所有被加载的结构
  • Class类是Reflection的根源,针对任何你想的动态加载、运行的类,唯有先获得相应的Class对象
package com.chen.reflection;

//测试Class类的创建方式有哪些
public class Test02 {
    public static void main(String[] args)  throws ClassNotFoundException{
        Person person = new Student();
        System.out.println("这个人是"+person.name);

        //方式一:通过对象获得
        Class c1 = person.getClass();
        System.out.println(c1.hashCode());
        //方式二:通过forname获得
        Class c2 = Class.forName("com.chen.reflection.Student");
        System.out.println(c2.hashCode());
        //方式三:通过类名.class获得
        Class c3 = Student.class;
        System.out.println(c3.hashCode());
        //方式四:基本内置类型的包装类都一个Type属性
        Class c4 = Integer.TYPE;
        System.out.println(c4);
        //获得父类类型
        Class c5 = c1.getSuperclass();
        System.out.println(c5);
    }
}
class Person{
    public String name;

    public Person(){
    }
    public Person(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                '}';
    }
}
class Student extends Person{
    public Student() {
        this.name = "学生";
    }
}
class Teacher extends Person{
    public Teacher(String name) {
        this.name = "老师";
    }
}
package com.chen.reflection;

import java.lang.annotation.ElementType;

//所有类型的Class
public class Test03 {
    public static void main(String[] args) {
        Class c1 = Object.class;//类
        Class c2 = Comparable.class;//接口
        Class c3 = String[].class;//一维数组
        Class c4 = int[][].class;//二维数组
        Class c5 = Override.class;//注解
        Class c6 = ElementType.class;//枚举
        Class c7 = Integer.class;//基本数据类型
        Class c8 = void.class;//void
        Class c9 = Class.class;//Class

        System.out.println(c1);
        System.out.println(c2);
        System.out.println(c3);
        System.out.println(c4);
        System.out.println(c5);
        System.out.println(c6);
        System.out.println(c7);
        System.out.println(c8);
        System.out.println(c9);

        //只要类型与维度一样,就是同一个Class
        int[] a = new int[10];
        int[] b = new int[100];
        System.out.println(a.getClass().hashCode());
        System.out.println(b.getClass().hashCode());
    }
}

类加载内存分析

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-as0qtRH0-1693047038431)(C:\Users\86152\AppData\Roaming\Typora\typora-user-images\image-20230826123555145.png)]

package com.chen.reflection;

public class Test04 {
    public static void main(String[] args) {
        A a = new A();
        System.out.println(A.m);
        /**
         1.加载到内存,会产生一个类对应的Class对象
         2、链接,链接结束后m=0
         3.初始化
            <clinit>(){
                 System.out.println("A类静态代码块初始化");
                 m=300;
                 m = 100;
            }
            m = 100;
         */
    }
}

class A{
    static {
        System.out.println("A类静态代码块初始化");
        m=300;
    }
    static int m = 100;
    public A(){
        System.out.println("A类的无参构造初始化");
    }
}

分析类初始化

package com.chen.reflection;

//测试类声明时候会初始化
public class Test05 {
    static {
        System.out.println("Main类被加载");
    }
    public static void main(String[] args) {
        //1.主动引用
        //Son son = new Son();

        //反射也会产生主动引用
        //Class.forName("com.chen.reflection.Son");

        //不会产生类的引用方法
        //System.out.println(Son.b);//子类调用父类的静态属性不会被加载

        Son[] array = new Son[5];//数组定义类引用,不会触发类的初始化
        
        System.out.println(Son.M);//常量不会触发类的初始化
    }
}
class  Father{
    static int b = 2;
    static {
        System.out.println("父类被加载");
    }
}
class Son extends Father{
    static {
        System.out.println("子类被加载");
        m=300;
    }
    static int m =100;
    static final int M=1;
}

类加载器

package com.chen.reflection;

public class Test06 {
    public static void main(String[] args) throws Exception{
        //获取系统类的加载器
        ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader();
        System.out.println(systemClassLoader);

        //获取系统类加载器的父类加载器------->扩展类加载器
        ClassLoader parent = systemClassLoader.getParent();
        System.out.println(parent);

        //获取扩展类加载器的父类加载器------->根加载器(C/C++)无法直接获取
        ClassLoader parent1 = parent.getParent();
        System.out.println(parent1);

        //测试当前类是哪个加载器加载的
        ClassLoader classLoader = Class.forName("com.chen.reflection.Test06").getClassLoader();
        System.out.println(classLoader);
        //测试JDK内置的类是谁加载的
        classLoader = Class.forName("java.lang.Object").getClassLoader();
        System.out.println(classLoader);

        //如何获得系统类加载器可以加载的路径
        System.out.println(System.getProperty("java.class.path"));
    }
}

获取运行时类的完整结构

package com.chen.reflection;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

//获取类的信息
public class Test07 {
    public static void main(String[] args) throws Exception{
        Class c1 = Class.forName("com.chen.reflection.User");

        //获取类的名字
        System.out.println(c1.getName());//获取包名 + 类型
        System.out.println(c1.getSimpleName());//获取类名

        //获取类的属性
        System.out.println("=======================");
        Field[] fields = c1.getFields();//只能找到public属性

        fields = c1.getDeclaredFields();//找到全部属性
        for (Field field:fields){
            System.out.println(field);
        }

        //获得指定属性的值
        Field name = c1.getDeclaredField("name");
        System.out.println(name);

        //获得类的方法
        System.out.println("=========================");
        Method[] methods = c1.getMethods();//获得本类及其父类的全部public方法
        for(Method method:methods){
            System.out.println("正常的:"+method);
        }
        methods = c1.getDeclaredMethods();//获得本类的所有方法
        for (Method method:methods){
            System.out.println("getDeclaredMethods:"+method);
        }

        //获得指定方法
        //重载,通过参数类型来判断需要的是哪个方法
        Method getName = c1.getMethod("getName", null);
        Method setName = c1.getMethod("setName", String.class);
        System.out.println(getName);
        System.out.println(setName);

        //获得类的构造器
        System.out.println("=========================");
        Constructor[] constructors = c1.getConstructors();
        for (Constructor constructor:constructors){
            System.out.println(constructor);
        }
        constructors = c1.getDeclaredConstructors();
        for (Constructor constructor:constructors){
            System.out.println("##"+constructor);
        }

        //获得指定的构造方法
        Constructor declaredConstructor = c1.getDeclaredConstructor(String.class,int.class,int.class);
        System.out.println("指定的构造器:"+declaredConstructor);
    }
}
package com.chen.reflection;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

//通过反射机制动态的创建对象
public class Test08 {
    public static void main(String[] args) throws Exception{
        //获得Class对象
        Class c1 = Class.forName("com.chen.reflection.User");
        
        //构造一个对象
        //调用Class对象的newInstance方法时:  1、类必须有一个无参数的构造器;2.类的构造器的访问权限需要足够
        User user = (User) c1.newInstance(); //本质是调用了类的无参构造器
        System.out.println(user);
        
        //通过构造器创建对象
        Constructor constructor = c1.getDeclaredConstructor(String.class, int.class, int.class);
        User user2 =(User) constructor.newInstance("lc", 001, 18);
        System.out.println(user2);

        //通过方法调用普通方法
        User user3 = (User) c1.newInstance();
        //通过反射获得一个方法
        Method setName = c1.getDeclaredMethod("setName", String.class);
        
        //invoke : 激活的意思
        //(对象,”方法的值“)
        setName.invoke(user3,"励志学好编程");
        System.out.println(user3.getName());
        
        //通过反射操作属性
        System.out.println("============================");
        User user4 = (User) c1.newInstance();
        Field name = c1.getDeclaredField("name");
        
        //不能直接操作私有(private)属性,需要关闭程序的安全检查,属性或者方法的setAccessible(true)
        name.setAccessible(true);
        
        name.set(user4,"励志学好编程2");
        System.out.println(user4.getName());
    }
}
package com.chen.reflection;

import java.lang.reflect.Constructor;
import java.lang.reflect.Method;

//分析性能问题
public class Test09 {
    //普通方式调用
    public static void test01(){
        User user = new User();
        long startTime = System.currentTimeMillis();
        for(int i=0;i<1000000000;i++){
            user.getName();
        }
        long endTime = System.currentTimeMillis();
        System.out.println("普通方式执行10亿次:"+(endTime-startTime)+"ms");
    }

    //反射方式调用
    public static void test02() throws Exception{
        User user = new User();
        Class c1 = user.getClass();

        Method getName = c1.getDeclaredMethod("getName", null);

        long startTime = System.currentTimeMillis();

        for(int i=0;i<1000000000;i++){
            getName.invoke(user,null);
        }

        long endTime = System.currentTimeMillis();
        System.out.println("反射方式执行10亿次:"+(endTime-startTime)+"ms");
    }
    //反射方式调用   关闭检测
    public static void test03() throws Exception{
        User user = new User();
        Class c1 = user.getClass();

        Method getName = c1.getDeclaredMethod("getName", null);
        getName.setAccessible(true);

        long startTime = System.currentTimeMillis();

        for(int i=0;i<1000000000;i++){
            getName.invoke(user,null);
        }

        long endTime = System.currentTimeMillis();
        System.out.println("关闭检测执行10亿次:"+(endTime-startTime)+"ms");
    }

    public static void main(String[] args) throws Exception{
        test01();
        test02();
        test03();
    }
}

获取泛型信息

package com.chen.reflection;

import com.sun.source.tree.ParameterizedTypeTree;

import java.lang.reflect.AnnotatedType;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;

//通过反射获取泛型
public class Test10 {

    public void test01(Map<String,User> map, List<User> list){
        System.out.println("test01");
    }
    public Map<String,User> test02(){
        System.out.println("test02");
        return null;
    }

    public static void main(String[] args) throws Exception{
        Method method = Test10.class.getMethod("test01", Map.class, List.class);
        Type[] genericParameterTypes = method.getGenericParameterTypes();
        for (Type genericParameterType : genericParameterTypes) {
            System.out.println("#"+genericParameterType);
            if(genericParameterType instanceof ParameterizedType){
                Type[] actualTypeArguments = ((ParameterizedType) genericParameterType).getActualTypeArguments();
                for (Type actualTypeArgument : actualTypeArguments) {
                    System.out.println(actualTypeArgument);
                }
            }
        }

        System.out.println("====================");

        method = Test10.class.getMethod("test02",null);
        Type genericReturnType = method.getGenericReturnType();

        if(genericReturnType instanceof ParameterizedType){
            Type[] actualTypeArguments = ((ParameterizedType) genericReturnType).getActualTypeArguments();
            for (Type actualTypeArgument : actualTypeArguments) {
                System.out.println(actualTypeArgument);
            }
        }
    }
}

获取注解信息

package com.chen.reflection;

import java.lang.annotation.*;
import java.lang.reflect.Field;

//练习反射操作注解
public class Test11 {
    public static void main(String[] args) throws Exception{
        Class c1 = Class.forName("com.chen.reflection.Student2");

        //通过反射获得注解
        Annotation[] annotations = c1.getAnnotations();
        for (Annotation annotation : annotations) {
            System.out.println(annotation);
        }

        //获得注解的value的值
        TableChen tableChen = (TableChen) c1.getAnnotation(TableChen.class);
        String value = tableChen.value();
        System.out.println(value);

        //获得类指定的注解
        Field f =c1.getDeclaredField("name");
        FieldChen annotation = f.getAnnotation(FieldChen.class);
        System.out.println(annotation.columnName());
        System.out.println(annotation.type());
        System.out.println(annotation.length());
    }
}
@TableChen("db_student")
class Student2{
    @FieldChen(columnName = "db_id",type = "int",length = 10)
    private int id;
    @FieldChen(columnName = "db_age",type = "int",length = 10)
    private int age;
    @FieldChen(columnName = "db_name",type = "varchar",length = 3)
    private String name;
    public Student2(){
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    @Override
    public String toString() {
        return "Student2{" +
                "id=" + id +
                ", age=" + age +
                ", name='" + name + '\'' +
                '}';
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Student2(int id, int age, String name){
        this.id = id;
        this.age = age;
        this.name = name;
    }
}

//类名的注解
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@interface TableChen{
    String value();
}

//属性的注解
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface  FieldChen{
    String columnName();
    String type();
    int length();
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值