注解和反射

注解和反射

1 注解

1.1 初识注解

>

1.2 内置注解

1.3 元注解

@Target表示我们可以将注解用在哪些地方
@Retention表示我们的注解在什么地方还有效
@Documented表示是否将我们的注解生成在JavaDoc中
@Inherited表示子类可以继承父类的注解

元注解标注在 注解定义的上边

1.4 自定义注解

//自定义注解
public class TestAnnotation1 {
    //注解可以显示赋值, 如果没有默认值,我们就必须给注解赋值
    @MyAnnotation1(schools = "你好")
    public void test(){

    }
    //如果注解只有value一个参数,那么默认可以不写参数名赋值
    @MyAnnotation2("123")
    public void test2(){

    }
}
@Target({ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation1{
    //注解的参数 : 参数类型+参数名 ();
    String name() default "";
    int age () default 18;
    int id() default -1;
    String[] schools();
}

@Target({ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation2{
    String value();
}

2 反射

2.1 静态 VS 动态语言

2.2 反射介绍


2.3 获取Class对象

public class TestReflection2 {

    public static void main(String[] args) throws ClassNotFoundException {
        //第一种方式:通过类名。class获取
        Class c1 = Person.class;
        //第二中方式获取: 对象.getClass()
        Person person1 = new Person("学生");
        Class c2 = person1.getClass();
        //第三中方式:Class.forName("全类名")
        Class c3 = Class.forName("反射.Person");
        //第四种方式:基本数据类型的包装类型用Type属性获取
        Class c4 = Integer.TYPE;
        System.out.println(c1.hashCode());
        System.out.println(c2.hashCode());
        System.out.println(c3.hashCode());
    }
}
class Person{
    String name;

    public String getName() {
        return name;
    }
}

2.4 所有类型的class对象

public class TestReflection3 {
    public static void main(String[] args) {
        Class c1=Override.class;
        Class c2=Class.class;
        Class c3=Integer.class;
        Class c4=void.class;
        Class c5=int[].class;
        Class c6=int[][].class;
        Class c7=Enum.class;
        Class c8=Runnable.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);
//只要是同类型的对象,class实例是唯一的
        int []a=new int[10];
        int []b=new int[100];
        System.out.println(a.getClass().hashCode());
        System.out.println(b.getClass().hashCode());
    }
}

2.5 类加载内存分析

类的加载过程

什么时候会发送类初始化

类加载器的作用

/*
补充:如果自己定义了一个java.lang.String类,那么这个类不会生效,
因为有双亲委派机制,会一层一层找,先找系统加载器,找到了就往上一层
找,直到找到最高层根加载器,如果有就用根加载器的
*/   

public class ClassLoader1 {
    public static void main(String[] args) throws ClassNotFoundException {
        //获取系统类加载器
        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);//java无法获取根加载器

        //测试当前类是哪个加载器加载的
        ClassLoader classLoader = Class.forName("反射.ClassLoader1").getClassLoader();
        System.out.println(classLoader);
    }
}

2.6 获取类的运行时结构

public class Test4 {

    public static void main(String[] args) throws Exception {
        User user=new User();
        Class c1 = user.getClass();

        Field[] fields = c1.getFields();//只能找到public属性
        for (Field field : fields) {
            System.out.println("正常:"+field);
        }
        fields=c1.getDeclaredFields();//获取所有的变量
        for (Field field : fields) {
            System.out.println("DeclaredField:"+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("DeclaredMethod:"+method);
        }
        Method setAge = c1.getMethod("setAge", int.class);//获取指定方法
        System.out.println("指定:"+setAge);
        System.out.println("======================");
        Constructor[] constructors = c1.getConstructors(); //只能获取public
        for (Constructor constructor : constructors) {
            System.out.println("正常:"+constructor);
        }
        constructors=c1.getDeclaredConstructors(); //获取本类的所有构造器
        for (Constructor constructor : constructors) {
            System.out.println("DeclaredConstructor:"+constructor);
        }
        Constructor constructor = c1.getConstructor(String.class, int.class, String.class);//获取指定构造器
        System.out.println(constructor);
    }
}
class User{
    private String name;
    private int age;
    private String sex;
    public String id;

    public User(String name, int age, String sex) {
        this.name = name;
        this.age = age;
        this.sex = sex;
    }
    public User(){

    }

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

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

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }
    private void test(){

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

2.7 动态创建对象、执行方法

public class Test5 {
    public static void main(String[] args) throws Exception{
        //利用反射创建对象,设置属性
        Class c1 = Class.forName("反射.User");

        //利用无参构造创建对象
        User user = (User)c1.newInstance();
        System.out.println(user);

        //拿到constructor有参构造器,创建对象
        Constructor constructor = c1.getDeclaredConstructor(String.class, int.class, String.class);
        user = (User) constructor.newInstance("狂神", 18, "男");
        System.out.println(user);
        //拿到field设置user属性
        Field name = c1.getDeclaredField("name");
        //不能直接操作私有属性,我们需要关闭程序的安全检测,属性或者方法的setAccessible(true)
        name.setAccessible(true);
        name.set(user,"狂神2");
        System.out.println(user.getName());

        //拿到方法,使用方法设置属性
        Method setName = c1.getDeclaredMethod("setName", String.class);
        setName.invoke(user,"狂神3");
        System.out.println(user.getName());
    }
}

2.8 性能对比分析

正常运行时间<反射运行方法,关闭安全检查时间<反射运行时间

2.9 反射获取泛型

反射获取方法参数泛型

反射获取方法返回值泛型

2.10 反射操作注解

public class Test6 {
    public static void main(String[] args) throws Exception{
        //利用反射操作注解
        Class c1 = Class.forName("反射.Student");
        //获取注解
        Annotation[] annotations = c1.getAnnotations();
        for (Annotation annotation : annotations) {
            System.out.println(annotation);
        }
        //获取注解的value值
        Table annotation = (Table)c1.getAnnotation(Table.class);
//        Annotation annotation = c1.getAnnotation(Table.class);
        String value=annotation.value();
        System.out.println(value);

        //获取列指定的注解
        java.lang.reflect.Field name = c1.getDeclaredField("sex");
        Field annotation1= name.getAnnotation(Field.class);
        System.out.println(annotation1.column());
        System.out.println(annotation1.type());
        System.out.println(annotation1.length());

    }
}
@Table("tb_student")
class Student{
    @Field(column = "name",type = "varchar",length = 3)
    private String name;
    @Field(column = "age",type = "int",length = 10)
    private int age;
    @Field(column = "sex",type = "varchar",length = 1)
    private String sex;
    public Student(){

    }
    public Student(String name, int age, String sex) {
        this.name = name;
        this.age = age;
        this.sex = sex;
    }

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

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

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }
}
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@interface Table{
    String value();
}
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface Field{
    String column();
    String type();
    int length();
}
posted @ 2021-11-09 00:10  让时间变成力量  阅读(38)  评论(0)    收藏  举报