首页 > 其他 > 详细

注解和反射

时间:2020-05-10 00:07:04      阅读:39      评论:0      收藏:0      [点我收藏+]

注解 和 反射

注解

https://www.runoob.com/w3cnote/java-annotation.html

自定义注解

package chapter;

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

//自定义注解
public class test01 {
    @MyAnnotation(name = "dafran", schools = {"清华,北大"})   //注解复制没有顺序
    public void test() {}

    @MyAnnotation2("6b92d6")
    public void test2() {}
}

//元注解
//@Target    表示注解可以用在那些地方
//@Retention   表示 我们的注解在什么地方还有效
//@Documented  表示我们的注解生成在JAVAdoc中
//@Inherited 子类可以继承父类的注解

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

    String[] schools();
}

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation2{
    String value();   //一个时建议用value 可以直接赋值
}

反射

https://www.cnblogs.com/hongten/p/hongten_java_reflection.html

Java Reflection:

?Reflection (反射) 是Java被视为动态语言的关键,反射机制允许程序在执行期借助于Reflection API取得任何类的内部信息,并能直接操作任意对象的内部属性及方法。

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

?加载完类之后,在堆内存的方法区中就产生了一一个Class类型的对象(一个类只有一个Class对象),这个对象就包含了完整的类的结构信息。我们可以通过这个对象看到类的结构。这个对象就像一面镜子,透过这个镜子看到类的结构,所以,我们形象的称之为:反射。

正常方式:引入需要的"包类”名称 ———> 通过new实例化 ———> 取得实例化对象

反射方式:实例化对象 ———> getClass()方法 ———> 得到完整的“包类” 名称

Java反射机制提供的功能 :

?在运行时判断任意一个对象所属的类

?在运行时构造任意一个类的对象

?在运行时判断任意一个类所具 有的成员变量和方法

? ?在运行时获取泛型信息

?在运行时调用任意一个对象的成员变量和方法

?在运行时处理注解

?生成动态代理 (一个机制)

?……

反射相关的主要API :

?java.lang.Class 代表一个类

?java.lang.reflect.Method 代表类的方法

?java.lang.reflect.Field 代表类的成员变量

?java.lang.reflect.Constructor 代表类的构造器

?……

package chapter9;

import com.oracle.webservices.internal.api.databinding.DatabindingMode;

//反射
public class test02 {
    public static void main(String[] args) throws ClassNotFoundException {
//        通过反射获得类的Class对象
        Class c1 = Class.forName("chapter9.User");
        System.out.println(c1);

        Class c2 = Class.forName("chapter9.User");
        Class c3 = Class.forName("chapter9.User");
        Class c4 = Class.forName("chapter9.User");


//        一个类在内存中只有一个class对象,一个类被加载后,类的整个结构都会被封装在Class对象中
        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;
    }

    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类 :

对象照镜子后(就是getClass()方法 )可以得到的信息:某个类的属性、方法和构造器、某个类到底实现了哪些接口。对于每个类而言, JRE都为其保留一个不变的Class类型的对象。一个Class对象包含了特定某个结构(class/interface/enum/annotation/primitive type/void/[])的有关信息。

?Class 本身也是一个类

?Class 对象只能由系统建立对象

?一个加载的类在JVM中只会有一个Class实例

?一个Class对象对应的是一个加载到JVM中的一个.class文件

?每个类的实例都会记得自己是由哪个Class实例所生成

?通过Class可以完整地得到一一个类中的所有被加载的结构

?Class类 是Reflection的根源,针对任何你想动态加载、运行的类,唯有先获得相应的Class对象

Class类的常用方法 :

方法名 功能说明
static ClassforName(String name) 返回指定类名name的Class对象
Object newlnstance() 调用缺省构造函数,返回Class对象的一个实例
getName() 返回此Class对象所表示的实体(类,接口,数组类或void)的名称。
Class getSuperClass() 返回当前Class对象的父类的Class对象
Class[] getinterfaces() 获取当前Class对象的接口
ClassLoader getClassLoader() 返回该类的类加载器
ConstructorD getConstructors() 返回一个包含某些Constructor对象的数组
Method getMothed(String name,Class.. T) 返回一-个Method对象,此对象的形参类型为paramType
Field[]getDeclaredFields() 返回Field对象的一个数组

获得Class类的实例

package chapter9;

//获得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());

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

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

        //方式四:基本内置的包装类都有一个Type属性
        Class c4 = Integer.TYPE;
        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 = "老师";
    }
}

哪些类型可以有Class对象?

?class: 外部类,成员(成员内部类,静态内部类),局部内部类,匿名内部类。

?interface: 接口

?[]:数组

?enum:枚举

?annotation: 注解@interface

?primitive type:基本数据类型

?void

package chapter9;

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

    }
}

获得类的运行时结构 :

package chapter9;

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

public class test04 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, NoSuchMethodException {
        Class c1 = Class.forName("chapter9.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 sex = c1.getDeclaredField("sex");     //去掉Declared只能取到public属性的值
        System.out.println(sex);

        //获得类的方法
        Method[] methods = c1.getMethods();     //获得本类及其父类的全部public方法
        for (Method method: methods) {
            System.out.println("one:"+method);
        }
        methods = c1.getDeclaredMethods();      //获得本类中所有的方法
        for (Method method: methods) {
            System.out.println("two:"+method);
        }

        //获得指定方法
        //重载时,方法名一样时,用值去判断
        Method getName = c1.getMethod("getName", null);
        Method setName = c1.getMethod("setName", String.class);
        System.out.println(setName);
        System.out.println(getName);

        //获得类的构造器
        Constructor[] constructors = c1.getConstructors();      //public类
        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, int.class);
        System.out.println("指定构造器"+declaredConstructor);
    }
}

class User {
    public String name;
    private int age;
    private int id;
    private int sex = 1;

    public User() {
    }

    public User(String name, int age, int id, int sex) {
        this.name = name;
        this.age = age;
        this.id = id;
        this.sex = sex;
    }

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public int getSex() {
        return sex;
    }

    public void setSex(int sex) {
        this.sex = sex;
    }

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

动态创建对象执行方法 :

package chapter9;

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

public class test05 {
    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException, NoSuchFieldException {
        Class c1 = Class.forName("chapter9.User");

        //构造一个对象
        User user = (User) c1.newInstance();    //本质上调用类的无参构造器
        System.out.println(user);

        //通过构造器创建对象
        Constructor constructor = c1.getDeclaredConstructor(String.class, int.class, int.class, int.class);
        User user2 = (User) constructor.newInstance("dafran", 01, 02, 03);      //可以没有无参构造器
        System.out.println(user2);

        //通过反射调用普通方法
        User user3= (User)c1.newInstance();
        //通过反射获得一个方法
        Method setName = c1.getDeclaredMethod("setName", String.class);
        setName.invoke(user3, "dafran");
        System.out.println(user3.getName());

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

        //不可以直接操作私有属性, 需要关闭程序的安全检测
        name.setAccessible(true);  //可访问的————可以访问私有属性
        name.set(user4, "cola");
        System.out.println(user4.getName());

    }
}

class User {
    public String name;
    private int age;
    private int id;
    private int sex = 1;

    public User() {
    }

    public User(String name, int age, int id, int sex) {
        this.name = name;
        this.age = age;
        this.id = id;
        this.sex = sex;
    }

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public int getSex() {
        return sex;
    }

    public void setSex(int sex) {
        this.sex = sex;
    }

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

性能对比分析 :

package chapter9;

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

public class test06 {

    //普通方式调用
    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)+"ms");
    }

    //反射方式调用
    public static void test02() 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 test03() 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 {
        test01();
        test02();
        test03();
    }
}
普通方式执行10亿次:4ms
反射方式执行10亿次:3136ms
关闭检测执行10亿次:1321ms

Process finished with exit code 0

获取泛型信息 :

package chapter9;

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 test07 {
    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 {
        Method method = test07.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(actualTypeArgument);
                }
            }
        }

        method = test07.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);
            }
        }

    }
}

反射操作泛型:

?Java采用泛型擦除的机制来引入泛型,Java中的泛型仅仅是给编译器javac使用的,确保数据的安全性和免去强制类型转换问题,但是, 一旦编译完成,所有和泛型有关的类型全部擦除

?为了通过反射操作这些类型,Java新增了ParameterizedType ,GenericArrayType,TypeVariable和WildcardType几种类型来代表不能被归一到Class类中的类型但是又和原始类型齐名的类型.

?ParameterizedType :表示一种参数化类型,比如Collection

?GenericArrayType :表示种元素类型是参数化类型或者类型变量的数组类型

?TypeVariable :是各种类型变量的公共父接口

?WildcardType :代表一种通配符类型表达式

获得注解信息 :

练习:ORM

  • 了解什么是ORM ?
    • Object relationship Mapping -->对象关系映射
class Student{
    int id;				//							id		name		age
    String name;		//			====>>			001		dafran		3
    int age;			//							002		cola		4
}

◆类和表结构对应

◆属性和字段对应

◆对象和记录对应

◆要求:利用注解和反射完成类和表结构的映射关系


package chapter9;

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

public class test08 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException {
        Class c1 = Class.forName("chapter9.Students");

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

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

        //获得类指定的注解
        Field f = c1.getDeclaredField("id");
        Fielddafran annotation = f.getAnnotation(Fielddafran.class);
        System.out.println(annotation.columnNmae());
        System.out.println(annotation.type());
        System.out.println(annotation.length());


    }
}

@Tabledafran("db_student")
class Students{
    @Fielddafran(columnNmae = "db_id",type = "int",length = 10)
    private int id;
    @Fielddafran(columnNmae = "db_age",type = "int",length = 10)
    private int age;
    @Fielddafran(columnNmae = "db_name",type = "varchar",length = 3)
    private String name;

    public Students() {
    }

    public Students(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 "Students{" +
                "id=" + id +
                ", age=" + age +
                ", name=‘" + name + ‘\‘‘ +
                ‘}‘;
    }
}

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

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

注解和反射

原文:https://www.cnblogs.com/dafran/p/12861084.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!