注解与反射

1. 什么叫反射

package com.hzu.reflection;
//什么叫反射
public class Test01 extends Object{

    public static void main(String[] args) throws ClassNotFoundException {
        //通过反射获取类的class对象
        /*获的Class的方法
        1.User.Class
        2.Class.forName("com.hzu.reflection.User");
        3.User user=new User();Class c1=user.getClass();
        */
        Class c1 = Class.forName("com.hzu.reflection.User");
        System.out.println(c1);

        //一个类在内存中,只有一个class对象
        //一个类被加载后,整个类的信息都会封装在Class对象中
        Class c2 = Class.forName("com.hzu.reflection.User");
        Class c3 = Class.forName("com.hzu.reflection.User");
        System.out.println(c2.hashCode());
        System.out.println(c3.hashCode());
    }

}
class User{
    private int id;
    private int age;
    private String name;
    public String sex;
    public User() {
    }
    private User(int id){
        this.id=id;
    }
    public User(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;
    }

    private void test(){

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

2. 元注解


package com.hzu.annotation;

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

public class Test01 extends Object{

    //@Override重写的注解
    @Override
    public String toString(){
        return super.toString();
    }
    //
    @SuppressWarnings("all")
    public void test02(){
        List list=new ArrayList();
    }
    //Deprecated 不推荐程序员使用,但是可以使用,或者存在更好的方式,已经过时
    @Deprecated
    public static void test(){
        System.out.println("Deprecated");
    }

    public static void main(String[] args) {
        test();
    }
}
package com.hzu.annotation;

import java.lang.annotation.*;

//元注解测试
@MyAnnotation
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.hzu.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 = "hqf",schools = {"大学","中学"})
    public void test(){

    }

    @MyAnnotation3("广州")
    public void test1(){

    }
}
@Target({ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation2{
    //注解的参数 数据类型+参数名()
    String name() default "";
    int age();
    int id() default -1;//默认值为-1,代表不存在,indexof,如果找不到就返回-1
    String[] schools() default {"哔哩哔哩大学"};
}

@Target({ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation3{
    //只有一个参数,并且参数名是value,在使用注解时,给参数赋值时value可以省略,但是如果参数名不是value,而是其他:name,参数名不能省略
    String value();
}


package com.hzu.annotation;

import java.lang.annotation.*;

//元注解测试
@MyAnnotation
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{}

3.所有类型的class

package com.hzu.reflection;

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

        int a[]=new int[10];
        int b[]=new int[100];
        //只要元素类型和维度一样,就是同一个class
        System.out.println(a.getClass().hashCode());
        System.out.println(b.getClass().hashCode());
    }
}

4.类加载的内存分析

package com.hzu.reflection;

/**
 * 类加载的内存分析
 */
public class Test04 {
    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=30;
     *          static int m=100;
     *      }
     */
}
class A{
    static {
        System.out.println("A类的静态代码块");
        m=30;
    }
    static int m=100;
    public A(){
        System.out.println("A类的构造函数");
    }
}
package com.hzu.reflection;

public class Test05 {
    static {
        System.out.println("Main类加载");
    }

    public static void main(String[] args) throws ClassNotFoundException {
        //1.主动引用
        //1.1new对象会导致类的初始化,子类初始化的时候要先初始化父类
        //Son son=new Son();
        //1.2反射,反射会导致类的初始化,子类初始化的时候要先初始化父类
        //Class.forName("com.hzu.reflection.Son");
        //2.不会产生类的引用的方法
        //2.1子类引用父类的静态变量,不会导致子类的初始化
        //System.out.println(Son.b);
        //2.2声明数组,不会初始化类
        //Son[]array=new Son[10];
        //2.3常量不会引起类(子类、父类)的初始化
        System.out.println(Son.M);
    }
}
class Father{
    static {
        System.out.println("父类加载");
    }
    static int b=10;
}
class Son extends Father{
    static {
        System.out.println("子类加载");
    }
    static int m=100;
    static final int M=50;
}

5.获取类的信息

package com.hzu.reflection;

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

//获取类的信息
public class Test06 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, NoSuchMethodException {
        Class c1 = Class.forName("com.hzu.reflection.User");
        //1.获得类的名字
        System.out.println("c1:"+c1.getName());//获得包名+类名
        System.out.println("c1:"+c1.getSimpleName());//获得类名
        /*User user=new User();
        Class c2 = user.getClass();
        System.out.println("c2:"+c2.getName());
        System.out.println("c2:"+c2.getSimpleName());*/

        //2获得类的属性
        //2.1getFields(public属性)
        System.out.println("==========getFields(public属性)===============");
        Field[] fields = c1.getFields();
        for (Field field : fields) {
            System.out.println(field);
        }
        //2.2getDeclaredFields(所有属性)
        System.out.println("==========getDeclaredFields(所有属性)===============");
        Field[] declaredFields = c1.getDeclaredFields();
        for (Field declaredField : declaredFields) {
            System.out.println(declaredField);
        }
        //2.3获取指定的属性
        Field name = c1.getDeclaredField("name");
        System.out.println("============获取指定的属性=============");
        System.out.println(name);

        //3.获得类的方法
        Method[] methods = c1.getMethods();//获得本类及其父类的所有public方法
        System.out.println("================getMethods()===========");
        for (Method method : methods) {
            System.out.println(method);
        }
        Method[] declaredMethods = c1.getDeclaredMethods();//获得本类的所有方法
        System.out.println("================getDeclaredMethods()===========");
        for (Method declaredMethod : declaredMethods) {
            System.out.println(declaredMethod);
        }
        //3.1获得指定的方法
        System.out.println("============获得指定的方法==================");
        Method getName = c1.getMethod("getName", null);
        Method setName = c1.getMethod("setName", String.class);
        System.out.println(getName);
        System.out.println(setName);
        //4.获得指定的构造器
        System.out.println("==============指定定构造器=============");
        Constructor[] constructors = c1.getConstructors();//获得public的构造器
        for (Constructor constructor : constructors) {
            System.out.println("constructor:"+constructor);
        }
        Constructor[] declaredConstructors = c1.getDeclaredConstructors();
        for (Constructor declaredConstructor : declaredConstructors) {
            System.out.println("declaredConstructor:"+declaredConstructor);
        }
        Constructor declaredConstructor = c1.getDeclaredConstructor(int.class, int.class, String.class);
        System.out.println(declaredConstructor);
    }
}


6.动态创建对象

package com.hzu.reflection;

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

//动态创建对象,通过反射
public class Test07 {
    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException, NoSuchFieldException {
        //1.获得Class对象
        Class c1 = Class.forName("com.hzu.reflection.User");
        //1.1构造一个对象
        User user = (User) c1.newInstance();//本质上调用类的public类型的无参构造函数创建对象
        System.out.println("user:"+user);
        //2.获得指定构造器来创建对象
        Constructor declaredConstructor = c1.getDeclaredConstructor(int.class, int.class, String.class);
        User user1 = (User) declaredConstructor.newInstance(10, 10, "小明");
        System.out.println("user1:"+user1);
        Constructor declaredConstructor1 = c1.getDeclaredConstructor(int.class);
        declaredConstructor1.setAccessible(true);
        User user2 =(User) declaredConstructor1.newInstance(20);//通过private的构造器,不能创建对象(报错),要向set访问权限
        System.out.println("user2:"+user2);
        //3.通过反射调用普通方法
        User user3=(User) c1.newInstance();
        //3.1获取一个方法
        Method setName = c1.getMethod("setName", String.class);
        //invoke:激活的意思
        //(对象,"方法的参数")
        setName.invoke(user3,"我的貂蝉在哪里");
        System.out.println(user3.getName());
        //3.2获取一个属性,通过反射操纵private要先设置权限
        User user4=(User)c1.newInstance();
        Field name = c1.getDeclaredField("name");
        //不能直接操作私有属性,我们需要关闭程序的安全检测,属性或者方法的setAccessible(true)
        name.setAccessible(true);//通过反射操纵private要先设置权限,取消安全检测
        name.set(user4,"吕布");
        System.out.println(user4.getName());
    }
}


7.性能检测

package com.hzu.reflection;

import com.sun.deploy.util.SystemUtils;
import sun.plugin2.util.SystemUtil;

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

//性能检测
public class Test08 {
    //普通调用
    public static void test01(){
        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)+"毫秒");
    }

    //通过反射调用
    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<1000000000;i++){
            getName.invoke(user,null);
        }
        long endTime = System.currentTimeMillis();
        System.out.println("通过反射调用10亿次:"+(endTime-startTime)+"毫秒");
    }
    //反射调用,关闭性能检测
    public static void test03() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        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<1000000000;i++){
            getName.invoke(user,null);
        }
        long endTime = System.currentTimeMillis();
        System.out.println("关闭性能检测调用10亿次:"+(endTime-startTime)+"毫秒");
    }

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

}


8.通过反射获取泛型

package com.hzu.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 Test09 {

    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 {
        System.out.println("==================test01===================");
        Method method = Test09.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(genericParameterType);
                }
            }
        }
        System.out.println("==================test02===================");
        method=Test09.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);
            }
        }
    }
}



9. 反射操作注解

package com.hzu.reflection;

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

//反射操作注解
public class Test10 {

    public static void main(String[] args) throws NoSuchFieldException {
        //获取类注解
        System.out.println("========获取类注解=============");
        Annotation[] annotations = Student2.class.getAnnotations();
        for (Annotation annotation : annotations) {
            System.out.println(annotation);
        }
        TableTop annotation = Student2.class.getAnnotation(TableTop.class);
        System.out.println(annotation.value());
        //获取属性注解
        System.out.println("========获取属性注解=============");
        Field field = Student2.class.getDeclaredField("name");
        FieldTop annotation1 = field.getAnnotation(FieldTop.class);
        System.out.println(annotation1.columName());
        System.out.println(annotation1.length());
        System.out.println(annotation1.type());

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

//自定义属性注解
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface FieldTop{
    String columName();
    String type();
    int length();
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值