Java注解与反射个人学习笔记

注解和反射

注解

什么是注解

内置注解

package com.siu.annotation;

import java.util.ArrayList;
import java.util.List;

// 什么是注解
public class Test01 extends Object {
    // @Override 重写的注解
    @Override
    public String toString() {
        return super.toString();
    }

    // Deprecated,不推荐使用但是可以使用,maybe存在更好的方式
    @Deprecated
    public static void test() {
        System.out.println("Siu~~~");
    }

    // SuppressWarnings("all")镇压警告,也可以放到类上面
    @SuppressWarnings("all")
    public void test02() {
        List list = new ArrayList();
    }

    public static void main(String[] args) {
        test();
    }
}

元注解

package com.siu.annotation;

import java.lang.annotation.*;

// 测试元注解
public class Test02 {
    @MyAnnotation
    public void test() {

    }
}

// 定义一个注解
// Target表示注解可以放在哪些地方
@Target(value = {ElementType.METHOD, ElementType.TYPE})
// Retention表示注解在哪些地方有效
// RUNTIME > CLASS >SOURCE
@Retention(value = RetentionPolicy.RUNTIME)
// Documented表示是否将注解生成带JAVAdoc中
@Documented
// Inherited 表示子类可以继承父类的注解
@Inherited
@interface MyAnnotation {

}

自定义注解

package com.siu.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(name = "SIU", schools = "RealMadrid")
    public void test() {}
    @MyAnnotation3("SIU")  // 只有一个参数且是value时,可以省略value
    public void test2(){}
}

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation2 {
    // 注解的参数:参数类型 + 参数名 + ()
    String name() default "";

    int age() default 0;

    int id() default -1;  // 如果默认值位-1,代表不存在

    String[] schools() default {"Barcelona", "Manchester United"};
}

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

反射

反射机制

静态VS动态语言

Java Reflection

Java 反射机制研究及应用

Java反射优缺点

主要API

package com.siu.reflection;

// 什么叫反射
public class Test02 extends Object {
    public static void main(String[] args) throws ClassNotFoundException {

        // 通过反射获取类的class对象
        Class c1 = Class.forName("com.siu.reflection.User");
        System.out.println(c1.hashCode());
        Class c2 = Class.forName("com.siu.reflection.User");
        Class c3 = Class.forName("com.siu.reflection.User");
        Class c4 = Class.forName("com.siu.reflection.User");
        // 一个类在内存中只有一个class对象
        // 一个类被加载后,类的整个结构都被封装在Class对象中
        System.out.println(c2.hashCode());
        System.out.println(c3.hashCode());
        System.out.println(c4.hashCode());
    }

}

// 实体类:pojo, entity
class User {
    private String name;
    private int id;
    private int age;

    public User() {

    }

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

    public String getName() {
        return name;
    }

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

    public int getId() {
        return id;
    }

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

    public int getAge() {
        return age;
    }

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

Class类

Class类常用方法

获取Class类的实例

package com.siu.reflection;


// 测试class类的创建方式有哪些
public class Test03 {
    public static void main(String[] args) throws ClassNotFoundException {
        Person person = new Student();
        System.out.println("这个人是:" + person.name);
        // 方式1:通过对象获得
        Class c1 = person.getClass();
        System.out.println(c1.hashCode());

        // 方式2:forName获得
        Class c2 = Class.forName("com.siu.reflection.Student");
        System.out.println(c2.hashCode());
        // 方式3:通过类名.class
        Class c3 = Student.class;
        System.out.println(c3.hashCode());
        // 方式4:基本内置的包装类都有一个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() {
        this.name = "老师";
    }
}

哪些类型可以有Class对象?

Java内存分析

类的加载与ClassLoader的理解

package com.siu.reflection;

public class Test05 {
    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.siu.reflection;

// 测试类肾么时候会初始化
public class Test06 {
    static {
        System.out.println("Main类被加载");
    }

    public static void main(String[] args) throws ClassNotFoundException {
        // 主动引用
        // Son son = new Son();

        // 反射也会产生主动引用
        // Class.forName("com.siu.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.siu.reflection;

public class Test07 {
    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);
        // 测试当前类是哪个加载器加载的
        ClassLoader classLoader = Class.forName("com.siu.reflection.Test07").getClassLoader();
        System.out.println(classLoader);
        // 测试JDK内置类是谁加载的
        classLoader = Class.forName("java.lang.Object").getClassLoader();
        System.out.println(classLoader);
        // 如何获得系统类加载器可以加载的路径
        String property = System.getProperty("java.class.path");
        System.out.println(property);
        // 双亲委派机制
            // java.lang.String-->
    }
}

获取运行时类的完整结构

package com.siu.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 ClassNotFoundException, NoSuchFieldException, NoSuchMethodException {
        Class c1 = Class.forName("com.siu.reflection.User");
        // 获得类的名字
        System.out.println(c1.getName());  // 获得包名+类名
        System.out.println(c1.getSimpleName());  // 获得类名
        System.out.println(new User().getName());
        // 获得类的属性
        System.out.println("================================");
        Field[] fields = c1.getFields();  // 只能找到public属性
        for (Field field : fields) {
            System.out.println(field);
        }
        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();  // 包括父类方法,包括private
        for (Method method : methods) {
            System.out.println(method);
        }
        System.out.println("================================");
        methods = c1.getDeclaredMethods();  // 不包括父类的方法,包括private
        for (Method method : methods) {
            System.out.println(method);
        }
        System.out.println("================================");
        Method getName = c1.getMethod("getName", null);  // 获得指定方法,参数内空null
        System.out.println(getName);

        // 获得指定构造器
        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 constructor = c1.getConstructor(String.class, int.class, int.class);
        System.out.println(constructor);
        System.out.println(c1.getConstructor(null));
    }
}

有了Class对象,能做肾么?

调用指定方法

setAccessible

package com.siu.reflection;

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

// 通过反射动态创建对象
public class Test09 {
    public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException, NoSuchFieldException {
        Class c1 = Class.forName("com.siu.reflection.User");
//        // 构造一个对象
//        User user = (User) c1.newInstance();  // 本质上是调用了类的无参构造器
//        System.out.println(user);

//        // 通过构造器创建对象
//        Constructor constructor = c1.getDeclaredConstructor(String.class, int.class, int.class);
//        User user2 = (User) constructor.newInstance("骡子", 007, 83);
//        System.out.println(user2);

        // 通过反射调用方法
        User user3 = (User) c1.newInstance();
        // 通过反射获取方法
        Method setName = c1.getDeclaredMethod("setName", String.class);
        // invoke激活
        // (对象, "方法的值")
        setName.invoke(user3, "骡子1");
        System.out.println(user3.getName());

        // 通过方法操作属性
        User user4 = (User) c1.newInstance();
        Field name = c1.getDeclaredField("name");
        // 不能直接操作私有属性,需要关闭程序的程序安全检测,属性或者方法的setAccessible(true)
        name.setAccessible(true);  // 关闭权限
        name.set(user4, "骡子2");
        System.out.println(user4.getName());
    }
}

性能分析

package com.siu.reflection;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

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

    // 反射方式调用
    public static void test02() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        User user = new User();
        Class c1 = user.getClass();
        Method getName = c1.getMethod("getName", null);
        long startTime = System.currentTimeMillis();
        for (int i = 0; i < 1_000_000_000; i++) {
            getName.invoke(user, null);
        }
        long endTime = System.currentTimeMillis();
        System.out.println("反射方式:" + (endTime - startTime) + "ms");
    }
    // 反射方法,关闭检测
    public static void test03() throws InvocationTargetException, IllegalAccessException, NoSuchMethodException {
        User user = new User();
        Class c1 = user.getClass();
        Method getName = c1.getMethod("getName", null);
        getName.setAccessible(true);  // 关闭权限
        long startTime = System.currentTimeMillis();
        for (int i = 0; i < 1_000_000_000; i++) {
            getName.invoke(user, null);
        }
        long endTime = System.currentTimeMillis();
        System.out.println("反射方式关闭检测:" + (endTime - startTime) + "ms");
    }

    public static void main(String[] args) throws InvocationTargetException, NoSuchMethodException, IllegalAccessException {
        test01();
        test02();
        test03();
    }
}

反射操作泛型(扩展)

package com.siu.reflection;

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 Test1 {
    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 NoSuchMethodException {
        Method method = Test1.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("========================================siu===================================");
        method = Test1.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);
            }
        }
    }
}

反射操作注解

练习:ORM

package com.siu.reflection;

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

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

        // 通过反射获得注解
        Annotation[] annotations = c1.getAnnotations();
        for (Annotation annotation : annotations) {
            System.out.println(annotation);
        }
        // 获得注解的value的值
        TableSiu table_siu = (TableSiu) c1.getAnnotation(TableSiu.class);
        String value = table_siu.value();
        System.out.println(value);
        // 获得类指定的注解
        Field f = c1.getDeclaredField("id");
        FiledSiu annotation = f.getAnnotation(FiledSiu.class);
        System.out.println(annotation.columnName());
        System.out.println(annotation.type());
        System.out.println(annotation.length());
    }
}

@TableSiu("Siu")
class Student2 {
    @FiledSiu(columnName = "db_id", type = "int", length = 10)
    private int id;
    @FiledSiu(columnName = "db_age", type = "int", length = 10)

    private int age;
    @FiledSiu(columnName = "db_name", type = "varchar", length = 3)
    private String name;

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

    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 int getId() {
        return id;
    }

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

    public Student2() {

    }

}

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

// 属性的注解
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@interface FiledSiu {
    String columnName();

    String type();

    int length();
}
posted @   还是啥都不会  阅读(18)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~
点击右上角即可分享
微信分享提示