首页 > 其他分享 >注解与反射

注解与反射

时间:2022-12-24 23:11:51浏览次数:52  
标签:反射 reflection System class println 注解 public out

  • 枚举
  • 反射 基本数据类型

注解

package com.annotation_reflection.annotation;
//注解
import java.util.ArrayList;
import java.util.List;

public class Test01 {
    @Override
    public String toString() {
        return super.toString();
    }
    @Deprecated
    public static void test(){
        System.out.println("Deprecated");
    }
    @SuppressWarnings("all")
    public void test2(){
        List list = new ArrayList();
    }

    public static void main(String[] args) {
        test();
    }
}
package com.annotation_reflection.annotation;
//元注解
import java.lang.annotation.*;

@MyAnnotation
public class MetaDemo02 {

    public void test(){

    }
}
//定义一个注解
//Target 表示我们的注解可以用在哪些地方。
@Target(value = {ElementType.METHOD, ElementType.TYPE})
//表示我们的注解在什么地方还有效.
//runtime>class>source
@Retention(value = RetentionPolicy.RUNTIME)
//表示是否将我们的注解生成在JAVADoc中
@Documented
//子类可以继承父类的注解
@Inherited
@interface MyAnnotation{

}
package com.annotation_reflection.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 = "lcj")
    public void test(){
    }
    @MyAnnotation3("asd")
    public void test2(){
    }
}
@Target(value = {ElementType.METHOD,ElementType.TYPE})
@Retention(value = RetentionPolicy.RUNTIME)
@interface MyAnnotation2{
    //注解的参数:参数类型+参数名()
    String name() default " ";
    int age() default 0;
    int id() default -1;//如果默认值为-1,代表不存在
    String[] school() default {"上海交通大学","复旦大学"};
}

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

反射

package com.annotation_reflection.reflection;

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

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

    private void test(){}

    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 +
                '}';
    }
}
package com.annotation_reflection.reflection;
//得到Class的几种方式
public class GetDemo02 {
    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);
        System.out.println(c1.hashCode());

        Class c2 = Class.forName("com.annotation_reflection.reflection.Student");
        System.out.println(c2.hashCode());

        Class c3 = Student.class;
        System.out.println(c3.hashCode());

        Class c4 = Integer.TYPE;
        System.out.println(c4);//int
        System.out.println(c4.hashCode());

        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 = "老师";
    }
}
package com.annotation_reflection.reflection;
//所有类型的class对象
import java.lang.annotation.ElementType;

public class AllDemo03 {
    public static void main(String[] args) {
        Class c1 = Object.class;
        Class c2 = Comparable.class;
        Class c3 = Override.class;
        Class c4 = ElementType.class;
        Class c5 = String[].class;
        Class c6 = int[][].class;
        Class c7 = Integer.class;
        Class c8 = void.class;
        Class c9 = Class.class;
        Class c10 = int.class;

        System.out.println(c1);//class java.lang.Object
        System.out.println(c2);//interface java.lang.Comparable
        System.out.println(c3);//interface java.lang.Override
        System.out.println(c4);//class java.lang.annotation.ElementType
        System.out.println(c5);//class [Ljava.lang.String;
        System.out.println(c6);//class [[I
        System.out.println(c7);//class java.lang.Integer
        System.out.println(c8);//void
        System.out.println(c9);//class java.lang.Class
        System.out.println(c10);//int

        //每个数组也属于一个类,该类反映为类对象,由具有相同元素类型和维数的所有数组共享。
        int[] a = new int[10];
        int[] b = new int[100];
        System.out.println(a.getClass().hashCode());//356573597
        System.out.println(b.getClass().hashCode());//356573597
    }
}

内存层面

package com.annotation_reflection.reflection;
//内存分析
public class MemoryAnalysis04 {
    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.annotation_reflection.reflection;
//什么时候会发生类初始化?
public class WhenToInit05 {
    static {
        System.out.println("main类被加载");
    }
    public static void main(String[] args) throws ClassNotFoundException {
        //1.主动引用
//        Son son = new Son();
//        System.out.println(Son.m);
        //反射也会产生主动引用
//        Class c1 = Class.forName("com.annotation_reflection.reflection.Son");

        //2.类的被动引用(不会发生类的初始化)
//        System.out.println(Son.a);

//        Son[] array = new Son[10];

        //引用常量不会触发此类的初始化(常量在链接阶段就存入调用类的常量池中了)
//        System.out.println(Son.M);
    }
}
class Father{
    static int a = 10;
    static {
        System.out.println("父类被加载");
    }
}
class Son extends Father{
    static {
        System.out.println("子类被加载");
        m = 300;
    }
    static int m = 100;
    static final int M = 2;
}

类加载器

package com.annotation_reflection.reflection;
//类加载器
public class ClassLoaderDemo06 {
    public static void main(String[] args) throws ClassNotFoundException {
        ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader();
        System.out.println(systemClassLoader);

        ClassLoader extClassLoader = systemClassLoader.getParent();
        System.out.println(extClassLoader);

        ClassLoader bootstrapClassLoader = extClassLoader.getParent();
        System.out.println(bootstrapClassLoader);

        ClassLoader classLoader = Class.forName("com.annotation_reflection.reflection.ClassLoaderDemo06")
                .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"));
        /*
        D:\Environment\Java\jdk1.8\jre\lib\charsets.jar;
        D:\Environment\Java\jdk1.8\jre\lib\deploy.jar;
        D:\Environment\Java\jdk1.8\jre\lib\ext\access-bridge-64.jar;
        D:\Environment\Java\jdk1.8\jre\lib\ext\cldrdata.jar;
        D:\Environment\Java\jdk1.8\jre\lib\ext\dnsns.jar;
        D:\Environment\Java\jdk1.8\jre\lib\ext\jaccess.jar;
        D:\Environment\Java\jdk1.8\jre\lib\ext\jfxrt.jar;
        D:\Environment\Java\jdk1.8\jre\lib\ext\localedata.jar;
        D:\Environment\Java\jdk1.8\jre\lib\ext\nashorn.jar;
        D:\Environment\Java\jdk1.8\jre\lib\ext\sunec.jar;
        D:\Environment\Java\jdk1.8\jre\lib\ext\sunjce_provider.jar;
        D:\Environment\Java\jdk1.8\jre\lib\ext\sunmscapi.jar;
        D:\Environment\Java\jdk1.8\jre\lib\ext\sunpkcs11.jar;
        D:\Environment\Java\jdk1.8\jre\lib\ext\zipfs.jar;
        D:\Environment\Java\jdk1.8\jre\lib\javaws.jar;
        D:\Environment\Java\jdk1.8\jre\lib\jce.jar;
        D:\Environment\Java\jdk1.8\jre\lib\jfr.jar;
        D:\Environment\Java\jdk1.8\jre\lib\jfxswt.jar;
        D:\Environment\Java\jdk1.8\jre\lib\jsse.jar;
        D:\Environment\Java\jdk1.8\jre\lib\management-agent.jar;
        D:\Environment\Java\jdk1.8\jre\lib\plugin.jar;
        D:\Environment\Java\jdk1.8\jre\lib\resources.jar;
        D:\Environment\Java\jdk1.8\jre\lib\rt.jar;
        D:\JavaProjects\JavaSE\out\production\basic grammar;
        D:\JavaProjects\JavaSE\basic grammar\lib\commons-io-2.11.0.jar;
        D:\JetBrains\IntelliJ IDEA 2022.1.3\lib\idea_rt.jar
         */

        //双亲委派机制

    }
}

反射相关操作

package com.annotation_reflection.reflection;
//获取类的运行时结构
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class GetStructure07 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, NoSuchMethodException {
        Class c1 = Class.forName("com.annotation_reflection.reflection.User");

        System.out.println(c1.getName());
        System.out.println(c1.getSimpleName());
        System.out.println("================================================");

        Field[] fields = c1.getFields();//只能找到public属性

        Field[] declaredFields = c1.getDeclaredFields();
        for (Field declaredField : declaredFields) {
            System.out.println(declaredField);
        }

        Field field = c1.getDeclaredField("name");
        System.out.println(field);
        System.out.println("=======================================================================");
        Method[] methods = c1.getMethods();//获得本类及其父类的全部public方法
        for (Method method : methods) {
            System.out.println(method);
        }
        System.out.println("-------------------------------------------------------------");
        Method[] methods1 = c1.getDeclaredMethods();//获得本类的所有方法
        for (Method method : methods1) {
            System.out.println(method);
        }
        System.out.println("----------------------------------------------------------------");
        Method method = c1.getMethod("setName",String.class);
        Method method1 = c1.getMethod("getName");
        System.out.println(method);
        System.out.println(method1);
        System.out.println("==================================================================");
        Constructor[] constructors = c1.getConstructors();
        for (Constructor constructor : constructors) {
            System.out.println(constructor);
        }

        Constructor[] constructors1 = c1.getDeclaredConstructors();
        for (Constructor constructor : constructors1) {
            System.out.println(constructor);
        }

        Constructor constructor = c1.getConstructor(String.class,int.class,int.class);
        System.out.println("##  "+ constructor);

    }
}
package com.annotation_reflection.reflection;
//通过反射动态地创建对象 执行方法 设置属性
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class DynamicDemo08 {
    public static void main(String[] args) throws Exception {
        Class c1 = Class.forName("com.annotation_reflection.reflection.User");

        //创建对象
        User user = (User)c1.newInstance();//本质是调用了类的无参构造器
        System.out.println(user);

        Constructor constructor = c1.getConstructor(String.class, int.class, int.class);
        User user1 = (User) constructor.newInstance("小明",001,18);
        System.out.println(user1);

        //执行方法
        User user2 = (User) c1.newInstance();
        Method method = c1.getMethod("setName",String.class);
        method.invoke(user2,"小红");//激活
        System.out.println(user2.getName());

        //设置属性
        User user3 = (User) c1.newInstance();
        Field field = c1.getDeclaredField("name");
        //不能直接操作私有属性,我们需要关闭程序的安全检测,属性或者方法或构造器的setAccessible(true)
        field.setAccessible(true);
        field.set(user3,"小张");
        System.out.println(user3.getName());
    }
}

性能分析

package com.annotation_reflection.reflection;

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

//性能对比分析
public class PerformanceAnalysis09 {
    public static void test1(){
        User user = new User();
        long startTime = System.currentTimeMillis();
        for (int i = 0; i < 10_0000_0000; i++) {
            user.getName();
        }
        long endTime = System.currentTimeMillis();
        System.out.println("正常调用:"+ (endTime-startTime) + "ms");
    }
    public static void test2() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        User user = new User();
        Class<? extends User> c1 = user.getClass();
        Method method = c1.getDeclaredMethod("getName",null);
        long startTime = System.currentTimeMillis();
        for (int i = 0; i < 10_0000_0000; i++) {
            method.invoke(user,null);
        }
        long endTime = System.currentTimeMillis();
        System.out.println("反射调用:"+ (endTime-startTime) + "ms");
    }
    public static void test3() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        User user = new User();
        Class<? extends User> c1 = user.getClass();
        Method method = c1.getDeclaredMethod("getName",null);
        method.setAccessible(true);
        long startTime = System.currentTimeMillis();
        for (int i = 0; i < 10_0000_0000; i++) {
            method.invoke(user,null);
        }
        long endTime = System.currentTimeMillis();
        System.out.println("关闭安全检测反射调用:"+ (endTime-startTime) + "ms");
    }

    public static void main(String[] args) throws InvocationTargetException, NoSuchMethodException, IllegalAccessException {
        test1();//正常调用:5ms
        test2();//反射调用:3396ms
        test3();//取消安全检测反射调用:1676ms
    }
}

获取泛型信息

package com.annotation_reflection.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 GetGenericity10 {
    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 Exception {
        Method method = GetGenericity10.class.getDeclaredMethod("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);
                }
            }
        }
        System.out.println("============================================================================");

        method = GetGenericity10.class.getDeclaredMethod("test2");
        Type genericReturnType = method.getGenericReturnType();
        System.out.println(genericReturnType);
        if (genericReturnType instanceof ParameterizedType){
            Type[] actualTypeArguments = ((ParameterizedType) genericReturnType).getActualTypeArguments();
            for (Type actualTypeArgument : actualTypeArguments) {
                System.out.println(actualTypeArgument);
            }
        }

    }
}

反射操作注解

package com.annotation_reflection.reflection;
//反射操作注解
import java.lang.annotation.*;
import java.lang.reflect.Field;

public class OperatingAnnotation11 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException {
        Class c1 = Class.forName("com.annotation_reflection.reflection.Student2");

        //类的注解
        Annotation[] annotations = c1.getAnnotations();
        for (Annotation annotation : annotations) {
            System.out.println(annotation);
        }
        System.out.println("--------------------------------");

        Table1 table1 = (Table1) c1.getAnnotation(Table1.class);
        System.out.println(table1);
        String value = table1.value();
        System.out.println(value);
        System.out.println("------------------------------------");

        //属性的注解
        Field field = c1.getDeclaredField("name");
        FieldA1 fieldA1 = field.getAnnotation(FieldA1.class);
        System.out.println(fieldA1.columnName());
        System.out.println(fieldA1.type());
        System.out.println(fieldA1.length());

    }
}
@Table1("db_student")
class Student2{
    @FieldA1(columnName = "db_id",type = "int",length = 10)
    private int id;
    @FieldA1(columnName = "db_age",type = "int",length = 10)
    private int age;
    @FieldA1(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 Table1{
    String value();
}

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface FieldA1 {
    String columnName();
    String type();
    int length();
}

标签:反射,reflection,System,class,println,注解,public,out
From: https://www.cnblogs.com/799rijiyuelei/p/17003518.html

相关文章