java的注解与反射

时间:2021-03-10 13:34:57   收藏:0   阅读:0

什么是注解

内置注解

元注解

 package com.lili.annotation;
 ?
 import java.lang.annotation.*;
 ?
 //测试元注解
 @MyAnnotation
 public class Test01{
     public void test(){}
 }
 //定义一个注解
 //Target表示注释范围,如:type,method...
 @Target(value = {ElementType.METHOD,ElementType.TYPE})
 //Retention表示有效范围,如:runtime,class,source
 @Retention(value = RetentionPolicy.RUNTIME)
 //Documented表示是否将我们的注释生成在JAVADOC中
 @Documented
 //Inherited 子类可以继承父类的注解
 @Inherited
 @interface MyAnnotation{
 }

自定义注解

 package com.lili.annotation;
 ?
 import java.lang.annotation.ElementType;
 import java.lang.annotation.Retention;
 import java.lang.annotation.RetentionPolicy;
 import java.lang.annotation.Target;
 ?
 public class Test02 {
     @MyAnnotation02(name = "大苏打",id = 2)
     public void Test(){}
 }
 @Target(value = {ElementType.METHOD,ElementType.TYPE})
 @Retention(RetentionPolicy.RUNTIME)
 @interface MyAnnotation02{
     //注解参数:参数类型+参数名
     String name() default "";
     int age() default 0;
     int id() default -1;
     String[] schools() default {"西部开源","清华大学"};
 }

JAVA Reflection

 Class c = Class.forName("java.lang.String")

Java反射机制提供的功能

Java反射的优缺点

优点:

缺点:

获得反射对象

 package com.lili.annotation;
 //什么叫反射
 public class Test03 {
     public static void main(String[] args) throws ClassNotFoundException {
         //通过反射获取类的Class对象
         Class c1 = Class.forName("com.lili.annotation.User");
         //一个类被加载以后,类的整体结构都被封装在class对象中
         System.out.println(c1);
 ?
    }
 }
 //实体类
 class User{
     private String name;
     private int id;
     private int age;
 ?
     public User(String name, int id, int age) {
         this.name = name;
         this.id = id;
         this.age = age;
    }
 ?
     public User() {
    }
 ?
     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的方式

 package com.lili.annotation;
 ?
 import java.lang.annotation.ElementType;
 import java.lang.annotation.Retention;
 import java.lang.annotation.RetentionPolicy;
 import java.lang.annotation.Target;
 ?
 public class Test02 {
     @MyAnnotation02(name = "大苏打",id = 2)
     public void Test(){}
 }
 @Target(value = {ElementType.METHOD,ElementType.TYPE})
 @Retention(RetentionPolicy.RUNTIME)
 @interface MyAnnotation02{
     //注解参数:参数类型+参数名
     String name() default "";
     int age() default 0;
     int id() default -1;
     String[] schools() default {"西部开源","清华大学"};
 }

哪些类型可以有Class对象

 package com.lili.annotation;
 ?
 import java.lang.annotation.ElementType;
 ?
 //所有类型的Class
 public class Test05 {
     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;
         Class c9 = 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);
         int[] a = new int[10];
         int[] b = new int[100];
         System.out.println(a.getClass().hashCode());
         System.out.println(b.getClass().hashCode());
    }
 }

类怎么加载

 package com.lili.annotation;
 //类怎么加载的
 public class Test06 {
     public static void main(String[] args) {
         A a = new A();
         System.out.println(a.m);
    }
 }
 class A{
     static {
         System.out.println("A类静态初始化!");
         m=100;
    }
     static int m = 200;
 ?
     public A() {
         System.out.println("A类无参构造方法");
    }
 }
 package com.lili.annotation;
 ?
 public class Test07 {
     static {
         System.out.println("main类被加载");
    }
     public static void main(String[] args) throws ClassNotFoundException {
         //主动引用
         //Son son = new Son();
         //反射也会产生主动引用
         //Class.forName("com.lili.annotation.Son");
         //不会产生类的引用方法
         //System.out.println(Son.f);
         Son[] sons = new Son[10];
         System.out.println(Son.m);
    }
 }
 class Father{
     static int f=3;
     static {
         System.out.println("父类被加载");
    }
 }
 class Son extends Father{
     static {
         System.out.println("子类被加载");
    }
     static int s = 100;
     static final int m=50;
 }

类加载器

 package com.lili.annotation;
 ?
 public class Test08 {
     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.lili.annotation.Test08").getClassLoader();
         System.out.println(classLoader);
         ClassLoader classLoader1 = Class.forName("java.lang.Object").getClassLoader();
         System.out.println(classLoader1);
         //获得系统类加载器可以加载的路径
         System.out.println(System.getProperty("java.class.path"));
    }
 }

获取运行时类的完整结构

通过反射获取运行时类的完整结构

 package com.lili.annotation;
 ?
 import java.lang.reflect.Field;
 import java.lang.reflect.Method;
 ?
 public class Test09 {
     public static void main(String[] args) {
         User user = new User();
         Class c1 = user.getClass();
         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);
        }
         System.out.println("=======================");
         //获得类的方法
         Method[] methods = c1.getMethods();
         for (Method method:methods) {
             System.out.println(method);
        }
         System.out.println("=======================");
         methods = c1.getDeclaredMethods();
         for (Method method:methods) {
             System.out.println(method);
        }
    }
 }

动态创建对象执行方法

 package com.lili.annotation;
 
 import java.lang.reflect.Constructor;
 import java.lang.reflect.Field;
 import java.lang.reflect.InvocationTargetException;
 import java.lang.reflect.Method;
 ?
 //创建动态对象,通过反射
 public class Test10 {
     public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException, NoSuchFieldException {
         //获得Class对象
         Class c1 = Class.forName("com.lili.annotation.User");
         //构造一个对象
         User user = (User) c1.newInstance();
         System.out.println(user);
         //通过构造器创造对象
         Constructor constructors = c1.getDeclaredConstructor(String.class,int.class,int.class);
         User user1 = (User)constructors.newInstance("白眉", 11, 500);
         System.out.println(user1);
         //通过反射调用普通方法
         User user2 = (User)c1.newInstance();
         //通过反射获取一个方法
         Method setName = c1.getDeclaredMethod("setName", String.class);
         setName.invoke(user2,"黑莓");
         System.out.println(user2.getName());
         //通过反射操作属性
         User user3 = (User)c1.newInstance();
         Field field = c1.getDeclaredField("name");
         field.setAccessible(true);//不能直接操作私有属性,关闭安全检测
         field.set(user3,"蓝莓");
         System.out.println(user3.getName());
    }
 }

性能对比分析

 package com.lili.annotation;
 ?
 import java.lang.reflect.InvocationTargetException;
 import java.lang.reflect.Method;
 ?
 public class Test11 {
     //普通方式调用
     public static void test1(){
         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 test2() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
         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 test3() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
         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 NoSuchMethodException, IllegalAccessException, InvocationTargetException {
         test1();
         test2();
         test3();
    }
 }

获取泛型信息

 package com.lili.annotation;
 ?
 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 Test12 {
     public void test1(Map<String,User> map, List<User> list){
         System.out.println("test1");
    }
     public Map<String,User> test2(){
         System.out.println("test2");
         return null;
    }
 ?
     public static void main(String[] args) throws NoSuchMethodException {
         Method method = Test12.class.getMethod("test1", 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);
                }
            }
        }
         method = Test12.class.getMethod("test2", null);
         Type genericReturnType = method.getGenericReturnType();
         if (genericReturnType instanceof ParameterizedType){
             Type[] actualTypeArguments = ((ParameterizedType) genericReturnType).getActualTypeArguments();
             for (Type actualTypeArgument : actualTypeArguments) {
                 System.out.println(actualTypeArgument);
            }
        }
    }
 }

获取注解信息

 package com.lili.annotation;
 ?
 import java.lang.annotation.*;
 import java.lang.reflect.Field;
 ?
 //练习反射操作注解
 public class Test13 {
     public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException {
         Class c1 = Class.forName("com.lili.annotation.Student1");
         //通过反射获得注解
         Annotation[] annotations = c1.getAnnotations();
         for (Annotation annotation : annotations) {
             System.out.println(annotation);
        }
         //获得注解的值
         TableMe tableMe = (TableMe) c1.getAnnotation(TableMe.class);
         String value = tableMe.value();
         System.out.println(value);
         //获得类指定的注解
         Field field = c1.getDeclaredField("name");
         FieldMe fa = field.getAnnotation(FieldMe.class);
         System.out.println(fa.columnName());
         System.out.println(fa.length());
         System.out.println(fa.type());
    }
 ?
 }
 @TableMe("student_db")
 class Student1{
     @FieldMe(columnName = "db_id",type = "int",length = 10)
     private int id;
     @FieldMe(columnName = "db_age",type = "int",length = 10)
     private int age;
     @FieldMe(columnName = "db_name",type = "varchar",length = 3)
     private String name;
 ?
     public Student1() {
    }
 ?
     public Student1(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 "Student1{" +
                 "id=" + id +
                 ", age=" + age +
                 ", name=‘" + name + ‘\‘‘ +
                 ‘}‘;
    }
 }
 //类名注解
 @Target(ElementType.TYPE)
 @Retention(RetentionPolicy.RUNTIME)
 @interface TableMe{
     String value();
 }
 //属性注解
 @Target(ElementType.FIELD)
 @Retention(RetentionPolicy.RUNTIME)
 @interface FieldMe{
     String columnName();
     String type();
     int length();
 }

 

 

 

 

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!