Java学习第二十五天 JavaSE 注解与反射

注解 Annotation----静态

什么是注解

    //Override 重写的注解
    @Override

内置注解

package com.Annotation;

import java.util.ArrayList;

public class Test01 extends Object{
    //Override ,重写的注解
    @Override
    public String toString(){
        return super.toString();
    }
    //不推荐使用但可以使用,过时的,危险的
    @Deprecated
    public static void test(){
        System.out.println("deprecated");
    }

    public static void main(String[] args) {
        test();
    }
    
    //镇压全部警告,标黄的就不出现了
    @SuppressWarnings("all")
    public void test02(){
        List list=new ArrayList<>();
    }
}

,被Deprecated注解划了,但是还可以用

元注解

package com.Annotation;

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

//测试元注解
@MyAnnotation//这里会报错,因为没有定义Target(value= ElementType.TYPE)
public class Test02 {
    @MyAnnotation
    public void test(){}
}
    //定义一个注解
    @Target(value= ElementType.METHOD)
    @interface MyAnnotation{

    }
package com.Annotation;

import java.lang.annotation.*;

//测试元注解
@MyAnnotation
public class Test02 {
    @MyAnnotation
    public void test(){}
}
//定义一个注解
//Target表示我们的注解可以用在哪些地方
@Target(value= {ElementType.METHOD,ElementType.TYPE })

//Retention 表示我们的注解在什么地方还有效
//runtime>class>sources
@Retention(value = RetentionPolicy.RUNTIME)

//Documented 表示是否将我们的注解生成在JAVAdoc中
@Documented

//Inherited 子类可以继承父类的注解
@Inherited
@interface MyAnnotation{}

自定义注解

package com.Annotation;

import java.lang.annotation.*;

public class Test03 {
    //注解可以显示赋值,如果没有默认值就必须给注解赋值
    @MyAnnotation2(name="因为定义的时候声明了要name,所以这里要输入",age=1)
    public void test(){}

    @MyAnnotation3("")//如果一个注解只有一个value值,可以省略 value=
    public void test02(){}
}

//元注解标明可以在哪些地方用
@Target({ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation2{
    //注解的参数:参数类型+参数名
    String name();
    // String name() default "";  这样就不用写名字了
    int age() default -1;//如果默认值为-1,代表不存在

    String[] schools() default "laji";
}

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

反射机制 Relection----动态

Java反射机制概述

静态与动态语言

反射机制让静态语言变成准动态语言

                            动态语言在程序运行时可以改变程序的结构

反射主要API

理解Class类并获取Class实例

Class类的常用方法

获取Class类的实例

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

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

//实体类pojo,entity
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;
    }
//alt+insert getter and setter
    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;
    }
//alt+insert toString
    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", id=" + id +
                ", age=" + age +
                '}';
    }
}
package com.Reflection;

//测试Class类的创建方式有哪些
public class Test02 {
    public static void main(String[] args) throws ClassNotFoundException {
        Preson person = new Student();
        System.out.println("这个人是:"+person.name);

        //方式一:通过对象获得
        Class c1 = person.getClass();
        System.out.println(c1.hashCode());

        //方式二:forName获得
        Class c2 = Class.forName("com.Reflection.Student");
        System.out.println(c2.hashCode());

        //方式三:通过类名.class获得
        Class c3 = Student.class;
        System.out.println(c3);//class com.Reflection.Student 类型
        System.out.println(c3.hashCode());

        //方式四:基本内置类型的包装类都有一个Type属性
        Class c4 = Integer.TYPE;
        System.out.println(c4);//返回 int 类型
        System.out.println(c4.hashCode());//返回的hashCode值与上面三类不一样

        //获得父类类型
        Class c5 = c1.getSuperclass();
        System.out.println(c5);//class com.Reflection.Preson,父类类型
    }
}

class Preson{
    String name;

    public Preson(){   }
    public Preson(String name){
        this.name=name;
    }

    @Override
    public String toString() {
        return "Preson{" +
                "name='" + name + '\'' +
                '}';
    }
}

class Student extends Preson{
    public Student(){
        this.name="学生";
    }

}class Teacher extends Preson{
    public Teacher(){
        this.name="老师";
    }
}

哪些类型有Class对象

package com.Reflection;

import java.lang.annotation.ElementType;

//所有类型的Class
public class Test04 {
    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 java.lang.Object
//        interface java.lang.Comparable
//        class [Ljava.lang.String;
//        class [[I
//        interface java.lang.Override
//        class java.lang.annotation.ElementType
//        class java.lang.Integer
//        void
//        class java.lang.Class


        //只要元素类型与维度一样,就是同一个Class
        int[]a=new int[10];
        int[]b=new int[100];
        System.out.println(a.getClass().hashCode());
        System.out.println(b.getClass().hashCode());//输出值相同


    }
}

类的加载与ClassLoader

Java内存分析

类加载过程

类的加载与ClassLoader理解

package com.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类的无参构造初始化");
    }
}
//A类静态代码块初始化
//A类的无参构造初始化
//100

什么时候发生类的初始化

类加载器

package com.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.Reflection.Test07").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"));
        
        //双亲委派机制
            //java.lang.String-->如果存在手写包的同名包,用默认的包,不会用自己的

        //sun.misc.Launcher$AppClassLoader@18b4aac2
        //sun.misc.Launcher$ExtClassLoader@4554617c
        //null
        //sun.misc.Launcher$AppClassLoader@18b4aac2
        //null
        /*   
C:\Program Files\Java\jdk1.8.0_151\jre\lib\charsets.jar;
C:\Program Files\Java\jdk1.8.0_151\jre\lib\deploy.jar;
C:\Program Files\Java\jdk1.8.0_151\jre\lib\ext\access-bridge-64.jar;
C:\Program Files\Java\jdk1.8.0_151\jre\lib\ext\cldrdata.jar;
C:\Program Files\Java\jdk1.8.0_151\jre\lib\ext\dnsns.jar;
C:\Program Files\Java\jdk1.8.0_151\jre\lib\ext\jaccess.jar;
C:\Program Files\Java\jdk1.8.0_151\jre\lib\ext\jfxrt.jar;
C:\Program Files\Java\jdk1.8.0_151\jre\lib\ext\localedata.jar;
C:\Program Files\Java\jdk1.8.0_151\jre\lib\ext\nashorn.jar;
C:\Program Files\Java\jdk1.8.0_151\jre\lib\ext\sunec.jar;
C:\Program Files\Java\jdk1.8.0_151\jre\lib\ext\sunjce_provider.jar;
C:\Program Files\Java\jdk1.8.0_151\jre\lib\ext\sunmscapi.jar;
C:\Program Files\Java\jdk1.8.0_151\jre\lib\ext\sunpkcs11.jar;
C:\Program Files\Java\jdk1.8.0_151\jre\lib\ext\zipfs.jar;
C:\Program Files\Java\jdk1.8.0_151\jre\lib\javaws.jar;
C:\Program Files\Java\jdk1.8.0_151\jre\lib\jce.jar;
C:\Program Files\Java\jdk1.8.0_151\jre\lib\jfr.jar;
C:\Program Files\Java\jdk1.8.0_151\jre\lib\jfxswt.jar;
C:\Program Files\Java\jdk1.8.0_151\jre\lib\jsse.jar;
C:\Program Files\Java\jdk1.8.0_151\jre\lib\management-agent.jar;
C:\Program Files\Java\jdk1.8.0_151\jre\lib\plugin.jar;
C:\Program Files\Java\jdk1.8.0_151\jre\lib\resources.jar;
C:\Program Files\Java\jdk1.8.0_151\jre\lib\rt.jar;
C:\Users\81909\Desktop\JavaSE\基础语法\src\com\oop\demo02\out\production\基础语法;
C:\TJUPT\IDEA\IntelliJ IDEA Community Edition 2021.1.1\lib\idea_rt.jar
         */

    }
}

创建运行时类的对象

获取运行时类的完整结构

package com.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.Reflection.User");



        //获得类的名字
        System.out.println(c1.getName());//包名+类名
        System.out.println(c1.getSimpleName());//类名

        //com.Reflection.User
        //User

        //获得类的属性
        System.out.println("========");
        Field[] fields = c1.getFields();//只能找到public属性

        fields=c1.getDeclaredFields();//找到全部属性
        for(Field field:fields){
            System.out.println(field);
        }
        //========
        //private java.lang.String com.Reflection.User.name
        //private int com.Reflection.User.id
        //private int com.Reflection.User.age

        //获得指定属性的值
        Field name=c1.getDeclaredField("name");//获得指定属性的值
        System.out.println(name);

        //private java.lang.String com.Reflection.User.name

        //获得类的方法
        System.out.println("=======");

        Method[] methods = c1.getMethods();//获得本类及父类的全部public方法
        for (Method method : methods) {
            System.out.println("正常的:"+method);
        }
        //=======
        //正常的:public java.lang.String com.Reflection.User.toString()
        //正常的:public java.lang.String com.Reflection.User.getName()
        //正常的:public int com.Reflection.User.getId()
        //正常的:public void com.Reflection.User.setName(java.lang.String)
        //正常的:public void com.Reflection.User.setAge(int)
        //正常的:public void com.Reflection.User.setId(int)
        //正常的:public int com.Reflection.User.getAge()
        //正常的:public final void java.lang.Object.wait() throws java.lang.InterruptedException
        //正常的:public final void java.lang.Object.wait(long,int) throws java.lang.InterruptedException
        //正常的:public final native void java.lang.Object.wait(long) throws java.lang.InterruptedException
        //正常的:public boolean java.lang.Object.equals(java.lang.Object)
        //正常的:public native int java.lang.Object.hashCode()
        //正常的:public final native java.lang.Class java.lang.Object.getClass()
        //正常的:public final native void java.lang.Object.notify()
        //正常的:public final native void java.lang.Object.notifyAll()

        Method[] declaredMethods = c1.getDeclaredMethods();//获得本类的全部方法,包含private等
        for (Method declaredMethod : declaredMethods) {
            System.out.println("getDeclaredMethods:"+declaredMethod);
        }

        //getDeclaredMethods:public java.lang.String com.Reflection.User.toString()
        //getDeclaredMethods:public java.lang.String com.Reflection.User.getName()
        //getDeclaredMethods:public int com.Reflection.User.getId()
        //getDeclaredMethods:public void com.Reflection.User.setName(java.lang.String)
        //getDeclaredMethods:public void com.Reflection.User.setAge(int)
        //getDeclaredMethods:public void com.Reflection.User.setId(int)
        //getDeclaredMethods:public int com.Reflection.User.getAge()

        //获得指定方法
        //重载
        Method getName = c1.getMethod("getName", null);
        System.out.println(getName);
        //public java.lang.String com.Reflection.User.getName()

        Method setName = c1.getMethod("setName", String.class);
        System.out.println(setName);
        //public void com.Reflection.User.setName(java.lang.String)


        //获得指定的构造器
        System.out.println("=======");
        Constructor[] constructors = c1.getConstructors();
        for (Constructor constructor : constructors) {
            System.out.println(constructor);
        }
        //public com.Reflection.User(java.lang.String,int,int)
        constructors = c1.getDeclaredConstructors();
        for (Constructor constructor : constructors) {
            System.out.println("##"+constructor);
        }
        //##public com.Reflection.User(java.lang.String,int,int)

        //获得指定的构造器
        Constructor declaredConstructor = c1.getDeclaredConstructor(String.class, int.class, int.class);
        System.out.println("指定构造器:"+declaredConstructor);
        //指定构造器:public com.Reflection.User(java.lang.String,int,int)
    }
}

小结

有了Class对象能干嘛

调用运行时类的指定结构

package com.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对象
        Class c1 = Class.forName("com.Reflection.User");

        //构造一个对象
         User user = (User) c1.newInstance();
         System.out.println(user);//本质是调用了类的无参构造器
        //User{name='null', id=0, age=0}

        //通过构造器创造对象
        Constructor constructor = c1.getDeclaredConstructor(String.class, int.class, int.class);
        User user2 = (User) constructor.newInstance("fuyi", 001, 25);
        System.out.println(user2);
        //User{name='fuyi', id=1, age=25}

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

        //通过反射操作属性
        User user4 = (User) c1.newInstance();
        Field name = c1.getDeclaredField("name");

        //不能直接操作私有属性,我们需要关闭程序的安全检测,需要属性或方法.setAccessible(true)
        name.setAccessible(true);//关掉权限,这样才能更改User里的private类
        name.set(user4,"wula");
        System.out.println(user4.getName());
        //wula
    }
}

调用指定的方法

setAccessible

分析性能问题

package com.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 < 10_0000_0000; i++) {
            user.getName();
        }

        long endTime=System.currentTimeMillis();//结束时调用系统时间

        System.out.println("普通方式执行十亿次时间:"+(endTime-startTime)+"ms");

    }

    //反射方式调用
    public static void test02() throws InvocationTargetException, IllegalAccessException, NoSuchMethodException {
        User user = new User();
        Class c1 = user.getClass();

        Method getName = c1.getDeclaredMethod("getName", null);

        long startTime=System.currentTimeMillis();//开始时调用系统时间

        for (int i = 0; i < 10_0000_0000; 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.getDeclaredMethod("getName", null);
        getName.setAccessible(true);

        long startTime=System.currentTimeMillis();//开始时调用系统时间

        for (int i = 0; i < 10_0000_0000; i++) {
            getName.invoke(user,null);
        }

        long endTime=System.currentTimeMillis();//结束时调用系统时间

        System.out.println("关闭检测,反射方式执行十亿次时间:"+(endTime-startTime)+"ms");
    }

    public static void main(String[] args) throws InvocationTargetException, IllegalAccessException, NoSuchMethodException {
        test01();
        test02();
        test03();
        //普通方式执行十亿次时间:2ms
        //反射方式执行十亿次时间:2091ms
        //关闭检测,反射方式执行十亿次时间:1129ms
    }
}

获取泛型信息

反射操作泛型

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

    public void test01(Map<String,User> map, List<User> list){ }

    public Map<String,User> test02(){ System.out.println("test02");return null; }

    public static void main(String[] args) throws NoSuchMethodException {
        Method method = Test11.class.getMethod("test01", Map.class, List.class);//获取方法

        //getGenericParameterTypes()  获得泛型的参数类型
        Type[] genericParameterTypes = method.getGenericParameterTypes();
        for (Type genericParameterType : genericParameterTypes) {
            System.out.println("$"+genericParameterType);
            //$java.util.Map<java.lang.String, com.Reflection.User>
            //$java.util.List<com.Reflection.User>

            //判断泛型参数类型是否为结构化参数类型
            if(genericParameterType instanceof ParameterizedType){
                //是的话就强转换为参数化类型,通过获得真实化参数方法getActualTypeArguments,获得数组打印
                Type[] actualTypeArguments = ((ParameterizedType) genericParameterType).
                        getActualTypeArguments();
                for (Type actualTypeArgument : actualTypeArguments) {
                    System.out.println(actualTypeArgument);
                }
            }
            //$java.util.Map<java.lang.String, com.Reflection.User>
            //class java.lang.String
            //class com.Reflection.User
            //$java.util.List<com.Reflection.User>
            //class com.Reflection.User
        }
         method = Test11.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);
            }
        }
        //class java.lang.String
        //class com.Reflection.User

    }
}

通过反射操作注解

ORM

package com.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.Reflection.Student2");

        //通过反射获得注解
        Annotation[] annotations = c1.getAnnotations();
        for (Annotation annotation : annotations) {
            System.out.println(annotation);
            //@com.Reflection.Tablefuiiy(value=db_student)
        }

        //获得注解的value的值
        Tablefuiiy tablefuiiy= (Tablefuiiy)c1.getAnnotation(Tablefuiiy.class);
        String value = tablefuiiy.value();
        System.out.println(value);
        //db_student

        //获得类指定的注解
        Field f = c1.getDeclaredField("name");
        Fieldfuyi annotation = f.getAnnotation(Fieldfuyi.class);
        System.out.println(annotation.columnName());
        System.out.println(annotation.type());
        System.out.println(annotation.length());
        //db_name
        //varchar
        //3
    }


}

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

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

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值