不想学习的小狐狸

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

元注解

元注解的作用就是负责注解其他注解,java定义了4个标准的meta-annotation类型,他们被用来提供对其他annotation类型作说明

这些类型和他们所支持的类在java.lang.annotation包中可以找到、

@Target:用于描述注解的使用范围

@Retention:表示需要在什么级别保存该注释信息,用于描述注解的生命周期(SOURCE<CLASS<RUNTIME)

@Document:说明该注解将被包含在javadoc中

@Inherited:说明子类可以继承父类中的该注解

自定义注解

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

//自定义注解
public class Test01 {
    //注解可以显示赋值,如果没有默认值,必须给注解赋值
    @MyAnnotation(age=18,name="kis")
    public void test(){
    }
    @MyAnnotation2("insong")
    public void test2(){

    }
}
@Target({ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation{
    //注解的参数:参数类型+参数名()
    String name() default "";
    int age();
    int id() default -1;//如果默认值为-1,代表不存在
    String[] schools() default {"喵喵喵","汪汪汪"};
}
@interface  MyAnnotation2{
    String value();
}

获得反射对象

//什么叫反射
public class Test01 {
    public static void main(String[] args) throws ClassNotFoundException {
        //通过反射获取类的class对象
        Class c1 = Class.forName("reflection.User");
        System.out.println(c1);

        Class c2 = Class.forName("reflection.User");
        Class c3 = Class.forName("reflection.User");
         //一个类在内存中只有一个Class对象
        //一个类被加载后,类的整个结构都会被封装在class对象中
        System.out.println(c2.hashCode());
        System.out.println(c3.hashCode());
    }
}
//实体类
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;
    }

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

得到class类的几种方式

//测试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());
        //方式2:forname获得
        Class c2 = Class.forName("reflection.Student");
        System.out.println(c2.hashCode());
        //方式3:通过类名.class获得
        Class c3 = Student.class;
        System.out.println(c3.hashCode());
        //方式4:基本内置类型的包装类都有一个type属性
        Class<Integer> 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对象

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());

    }
}

类加载器

public class Test04 {
    public static void main(String[] args) throws ClassNotFoundException {
        //获取系统类的加载器
        ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader();
        System.out.println(systemClassLoader);
        //获取系统类加载器的父类加载器-》扩展类加载器
        ClassLoader parent = systemClassLoader.getParent();
        System.out.println(parent);
        //获取扩展类加载器的父类加载器-》根加载器
        ClassLoader parent1 = parent.getParent();
        System.out.println(parent1);
        //测试当前类是哪个加载器加载的
        ClassLoader classLoader = Class.forName("reflection.Test04").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"));
    }
}

获取类的运行时结构

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

//获得类的信息
public class Test05 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, NoSuchMethodException {
        Class c1 = Class.forName("reflection.User");

        //获得类的名字
        System.out.println(c1.getName());//获得包名+类名
        System.out.println(c1.getSimpleName());//获得类名
        //获得类的属性
        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);
        //获得类的方法
        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);
        //获得指定的构造器
        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);
    }
}

动态创建对象执行方法

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

//动态的创建对象,通过反射
public class Test06 {
    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException, NoSuchFieldException {
        //获得class对象
        Class c1 = Class.forName("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("喵喵", 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");
        //不能直接操作私有属性,需要关闭程序的安全检测
        name.setAccessible(true);
        name.set(user4,"汪汪");
        System.out.println(user4.getName());

    }
}

获取注解信息

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

//练习反射操作注解
public class Test07 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException {
        Class c1 = Class.forName("reflection.Student2");
        //通过反射获得注解
        Annotation[] annotations = c1.getAnnotations();
        for(Annotation annotation :annotations){
            System.out.println(annotation);
        }
        //获得注解的value的值
        Tablekis tablekis = (Tablekis) c1.getAnnotation(Tablekis.class);
        String value = tablekis.value();
        System.out.println(value);
        //获得类指定的注解
        Field f = c1.getDeclaredField("name");
        Fieldkis annotation = f.getAnnotation(Fieldkis.class);
        System.out.println(annotation.columnName());
        System.out.println(annotation.type());
        System.out.println(annotation.length());

    }

}

@Tablekis("db_student")
class Student2{
    @Fieldkis(columnName = "db_id",type = "int",length = 10)
    private int id;
    @Fieldkis(columnName = "db_age",type = "int",length = 10)
    private int age;
    @Fieldkis(columnName = "db_name",type = "varchar",length =3)
    private String name;

    public Student2() {
    }

    public Student2(int id, int age, String name) {
        this.id = id;
        this.age = age;
        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;
    }

    public String getName() {
        return name;
    }

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

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

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

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

 

posted on 2021-05-26 17:59  一只小狐狸kis  阅读(51)  评论(0编辑  收藏  举报