Java--注解与反射--类加载器、类的运行时结构、反射动态创建对象、分析反射性能问题、反射操作泛型、反射操作注解

Java–注解与反射–类加载器、类的运行时结构、反射动态创建对象、分析反射性能问题、反射操作泛型、反射操作注解

类加载器

package com.zy.reflection;

/**
 *description: Java--注解与反射--类加载器
 *@program: 基础语法
 *@author: zy
 *@create: 2023-04-01 21:18
 */
public class Study05 {

    public static void main(String[] args) throws ClassNotFoundException {

        // 获得系统类加载器
        ClassLoader loader = ClassLoader.getSystemClassLoader();
        System.out.println(loader);
        // 获得系统类加载器父类:扩展类加载器
        ClassLoader loaderParent = loader.getParent();
        System.out.println(loaderParent);
        // 获得扩展类加载器父类:跟加载器(C/C++编写)
        ClassLoader loaderParentParent = loaderParent.getParent();
        System.out.println(loaderParentParent);
        // 获取当前类是哪个加载器加载
        ClassLoader classLoader = Class.forName("com.zy.reflection.Study05").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"));
        // 双亲委派机制:多重检测,若已存在加载器中的包,则手写无效
    }
}

类的运行时结构

package com.zy.reflection;

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

/**
 *description: Java--注解与反射--类的运行时结构
 *@program: 基础语法
 *@author: zy
 *@create: 2023-04-01 21:31
 */
public class Study06 {

    public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, NoSuchMethodException {
        Class<?> c1 = Class.forName("com.zy.reflection.User");

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

        // 获得类的属性
        Field[] fields = c1.getFields();// 公开属性获取
        fields = c1.getDeclaredFields();// 所有属性获取
        for (int i = 0; i < fields.length; i++) {
            System.out.println(fields[i]+"==>");
        }
        Field userName = c1.getDeclaredField("name");
        System.out.println(userName);

        // 获得类的方法
        Method[] methods = c1.getMethods();// 本类及父类全部公共方法
        for (Method method : methods) {
            System.out.println("公共的:"+method);
        }
        methods = c1.getDeclaredMethods();// 本类全部方法
        for (Method method : methods) {
            System.out.println("全部的:"+method);
        }
        // 获取方法时的参数为了避免重载方法无法识别
        Method getName = c1.getMethod("getName", null);
        Method setName = c1.getMethod("setName", String.class);
        System.out.println(getName);
        System.out.println(setName);

        // 获得类的构造器
        Constructor<?>[] constructors = c1.getConstructors();
        for (Constructor<?> constructor : constructors) {
            System.out.println(constructor);
        }
        constructors = c1.getDeclaredConstructors();
        for (Constructor<?> constructor : constructors) {
            System.out.println(constructor);
        }
        System.out.println(c1.getConstructor(null));
        System.out.println(c1.getConstructor(String.class, int.class, int.class));
    }
}

反射动态创建对象

package com.zy.reflection;

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

/**
 *description: Java--注解与反射--反射动态创建对象
 *@program: 基础语法
 *@author: zy
 *@create: 2023-04-01 21:53
 */
public class Study07 {

    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException,
            InstantiationException, NoSuchMethodException, InvocationTargetException, NoSuchFieldException {

        Class<?> c1 = Class.forName("com.zy.reflection.User");

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

        // 构造器创建对象
        Constructor<?> constructor = c1.getConstructor(String.class,int.class,int.class);
        user = (User)constructor.newInstance("zhangsan", 101, 18);
        System.out.println(user);

        // 调用方法
        Method setName = c1.getMethod("setName",String.class);
        // 激活:对象,方法的值
        setName.invoke(user,"lisi");
        System.out.println(user);

        // 操作属性
        Field userName = c1.getDeclaredField("name");
        // 是否取消语言安全检查,默认打开:私有的方法或者属性可操作赋值
        userName.setAccessible(true);
        // 对象,属性的值
        userName.set(user,"wangwu");
        System.out.println(user);
    }
}

分析反射性能问题

package com.zy.reflection;

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

/**
 *description: Java--注解与反射--分析反射性能问题
 *@program: 基础语法
 *@author: zy
 *@create: 2023-04-01 22:17
 */
public class Study08 {

    // 普通方式调用
    public static void study01(){
        User user = new User();
        long start = System.currentTimeMillis();
        for (int i = 0; i < 2000000000; i++) {
            user.getName();
        }
        long end = System.currentTimeMillis();
        System.out.println("普通方式执行20亿次:"+(end-start)+"ms");
    }

    // 反射方式调用
    public static void study02() throws NoSuchMethodException, InvocationTargetException,
            IllegalAccessException, InstantiationException {
        Class<User> c1 = User.class;
        User user = c1.newInstance();
        Method getName = c1.getMethod("getName", null);
        long start = System.currentTimeMillis();
        for (int i = 0; i < 2000000000; i++) {
            getName.invoke(user,null);
        }
        long end = System.currentTimeMillis();
        System.out.println("反射方式执行20亿次:"+(end-start)+"ms");
    }

    // 关闭检测后的反射方式调用
    public static void study03() throws NoSuchMethodException, InvocationTargetException,
            IllegalAccessException, InstantiationException {
        Class<User> c1 = User.class;
        User user = c1.newInstance();
        Method getName = c1.getMethod("getName", null);
        getName.setAccessible(true);
        long start = System.currentTimeMillis();
        for (int i = 0; i < 2000000000; i++) {
            getName.invoke(user,null);
        }
        long end = System.currentTimeMillis();
        System.out.println("关闭检测后的反射方式执行20亿次:"+(end-start)+"ms");
    }

    public static void main(String[] args) throws NoSuchMethodException, InstantiationException,
            IllegalAccessException, InvocationTargetException {
        study01();
        study02();
        study03();
    }
}

反射操作泛型

package com.zy.reflection;

import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;

/**
 *description: Java--注解与反射--反射操作泛型
 *@program: 基础语法
 *@author: zy
 *@create: 2023-04-01 22:32
 */
public class Study09 {

    public static void study01(Map<String,User> map, List<User> list){
        System.out.println("study01");
    }
    public static Map<String,User> study02(){
        System.out.println("study02");
        return null;
    }

    public static void main(String[] args) throws NoSuchMethodException {

        Method study01 = Study09.class.getMethod("study01", Map.class, List.class);
        Type[] types = study01.getGenericParameterTypes();
        for (Type type : types) {
            System.out.println(type);
            if(type instanceof ParameterizedType){
                Type[] actualTypeArguments = ((ParameterizedType) type).getActualTypeArguments();
                for (Type actualTypeArgument : actualTypeArguments) {
                    System.out.println(actualTypeArgument+"==");
                }
            }
        }

        Method study02 = Study09.class.getMethod("study02");
        Type genericReturnType = study02.getGenericReturnType();
        System.out.println(genericReturnType.getTypeName());
        if(genericReturnType instanceof ParameterizedType){
            Type[] actualTypeArguments = ((ParameterizedType) genericReturnType).getActualTypeArguments();
            for (Type actualTypeArgument : actualTypeArguments) {
                System.out.println(actualTypeArgument+"==>");
            }
        }
    }
}

反射操作注解

package com.zy.reflection;

import java.lang.annotation.Annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Field;

/**
 *description: Java--注解与反射--反射操作注解
 * 简单ORM实现:对象关系映射
 *@program: 基础语法
 *@author: zy
 *@create: 2023-04-01 22:47
 */
public class Study10 {

    public static void main(String[] args) throws NoSuchFieldException {
        Class<Student> studentClass = Student.class;

        // 获取类注解
        Annotation[] annotations = studentClass.getAnnotations();
        for (Annotation annotation : annotations) {
            System.out.println(annotation);
        }
        // 获取类注解的值
        TableORM tableORM = studentClass.getAnnotation(TableORM.class);
        String tableORMValue = tableORM.value();
        System.out.println(tableORMValue);

        // 获取类指定的注解
        Field id = studentClass.getDeclaredField("id");
        FieldORM idAnnotation = id.getAnnotation(FieldORM.class);
        System.out.println(idAnnotation.columnName());
        System.out.println(idAnnotation.columnType());
        System.out.println(idAnnotation.columnLength());
    }
}

@TableORM("db_student")
class Student{
    @FieldORM(columnName = "intid",columnType = "int",columnLength = 9)
    private int id;
    @FieldORM(columnName = "strname",columnType = "varchar2",columnLength = 30)
    private String name;
    @FieldORM(columnName = "intage",columnType = "int",columnLength = 9)
    private int age;

    public Student() {
    }

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

    public int getId() {
        return id;
    }

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

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

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

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

// 属性的注解
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface FieldORM{
    String columnName();
    String columnType();
    int columnLength();
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值