美文网首页
Java中的反射

Java中的反射

作者: GoLearning轻松学 | 来源:发表于2022-01-13 11:22 被阅读0次

    获取反射的类

    //获取反射的类
        public static void printReflectionClass() throws Exception {
            Fruit fruit = new Fruit();
            Class<?> class1 = fruit.getClass();
            System.out.println(class1);
            Class<?> class2 = Fruit.class;
            System.out.println(class2);
            Class<?> class3 = Class.forName("com.golearning.learning.bean.Fruit");
            System.out.println(class3);
        }
    

    运行结果:
    class com.golearning.learning.bean.Fruit
    class com.golearning.learning.bean.Fruit
    class com.golearning.learning.bean.Fruit

    获取一下传入的类的属性和类型

        /**
         * 获取一下传入的类的属性和类型
         * @param cla
         */
        public static void getRefClassField(Class<?> cla){
            Field[] fields = cla.getDeclaredFields();
            for (Field field : fields) {
                System.out.println(field.getName()+" = "+field.getType());
            }
    
        }
    
            Class<?> cla = Class.forName("com.golearning.learning.bean.Fruit");
            getRefClassField(cla);
    

    运行结果为:
    size = int
    color = class java.lang.String
    shape = class java.lang.String

    获取一下传入的类里面的方法

        /**
         * 获取一下传入的类里面的方法
         * @param cla
         */
        public static void getRefClassMethod(Class<?> cla) throws NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException {
            Method[] methods = cla.getDeclaredMethods();
            for (Method method : methods) {
                //获取方法的名字和有参参数个数数
                System.out.println(method.getName() + " == 参数个数 == "+method.getParameterCount());
                //获取方法的参数类型
                Class[] classes = method.getParameterTypes();
                for (Class aClass : classes) {
                    System.out.println(aClass);
                }
            }
            //执行反射获取到的方法
            Method method1 = cla.getDeclaredMethod("setColor",String.class);
            Object object = cla.newInstance();
            method1.invoke(object,"红色");
            System.out.println(object);
    
        }
    

    给一个泛型List 插入一条非泛型的数据

        /**
         * 给一个泛型List 插入一条非泛型的数据
         * @param list
         * @throws NoSuchMethodException
         * @throws InvocationTargetException
         * @throws IllegalAccessException
         */
        public static void addDataInGenericList(List<String> list) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
            //获取它的类
            Class<?> cla = list.getClass();
            //获取它的add方法 参数为任意对象
            Method method = cla.getDeclaredMethod("add",Object.class);
            method.invoke(list,514);
            for (Object o : list) {
                System.out.println(o);
            }
        }
    
            List<String> list = new ArrayList<>();
            list.add("爷爷今年有");
            list.add("99了");
            //给一个泛型List 插入一条非泛型的数据
            addDataInGenericList(list);
    

    运行结果:
    爷爷今年有
    99了
    514

    获取传入类的构造器创建对象

    public class Fruit {
        //大小
        private Integer size;
        //颜色
        private String color;
        //形状
        private String shape;
    
        public Fruit(Integer size, String color, String shape) {
            System.out.println("=====================获取有参构造器===================");
            this.size = size;
            this.color = color;
            this.shape = shape;
        }
    
        public Fruit() {
            System.out.println("=====================获取无参构造器===================");
        }
    
        public int getSize() {
            return size;
        }
    
        public void setSize(Integer size) {
            this.size = size;
        }
    
        public String getColor() {
            return color;
        }
    
        public void setColor(String color) {
            this.color = color;
        }
    
        public String getShape() {
            return shape;
        }
    
        public void setShape(String shape) {
            this.shape = shape;
        }
    
        @Override
        public String toString() {
            return "Fruit{" +
                    "size=" + size +
                    ", color='" + color + '\'' +
                    ", shape='" + shape + '\'' +
                    '}';
        }
    }
    
        /**
         * 获取传入类的构造器创建对象
         * @param cla
         */
        public static void getRefClassConstractor(Class<?> cla) throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
           //获取无参构造器
            Constructor<?> constructor =  cla.getConstructor(null);
            Object object = constructor.newInstance(null);
            System.out.println(object);
            //获取有参构造器
            Constructor<?> constructor2 =  cla.getConstructor(Integer.class,String.class,String.class);
            Object object2 = constructor2.newInstance(40,"红色","圆形");
            System.out.println(object2);
        }
    
              Class<?> cla = Class.forName("com.golearning.learning.bean.Fruit");
              getRefClassConstractor(cla);
    

    运行结果为:
    =====================获取无参构造器===================
    Fruit{size=null, color='null', shape='null'}
    =====================获取有参构造器===================
    Fruit{size=40, color='红色', shape='圆形'}

    注解的反射

    在一个类中使用注解

    //多个属性之间要用逗号隔开,赋值方式在括号内以value = ""的方式。
    @AnnotationClass(height = 11,shape = "ddd",deep = 45)
    public class Plants {
        private int height;
        private String shape;
        private int deep;
        private int width;
    
        public Plants(int height, String shape, int deep, int width) {
            this.height = height;
            this.shape = shape;
            this.deep = deep;
            this.width = width;
        }
    
        public Plants() {
        }
    
        public int getHeight() {
            return height;
        }
    
        public void setHeight(int height) {
            this.height = height;
        }
    
        public String getShape() {
            return shape;
        }
    
        public void setShape(String shape) {
            this.shape = shape;
        }
    
        public int getDeep() {
            return deep;
        }
    
        public void setDeep(int deep) {
            this.deep = deep;
        }
    
        public int getWidth() {
            return width;
        }
    
        public void setWidth(int width) {
            this.width = width;
        }
    
        @Override
        public String toString() {
            return "Plants{" +
                    "height=" + height +
                    ", shape='" + shape + '\'' +
                    ", deep=" + deep +
                    ", width=" + width +
                    '}';
        }
    }
    
    

    定义一个注解

    @Target(ElementType.TYPE) //表示AnnotationClass注解可以用于什么地方,可用于给一个类型进行注解,比如类、接口、枚举
    @Retention(RetentionPolicy.RUNTIME)//表示AnnotationClass注解传递存活时间,注解可保留到程序运行时被加载到JVM中
    public @interface AnnotationClass
    {
        //Integer heightx();//不能使用封装类型
        int height();//参数的类型只能是基本类型
        String shape();
        int deep();
        int width() default 10;
    
    }
    

    获取传入类的注解属性

        /**
         * 获取传入类的注解属性
         * @param cla
         */
        public static void getAnnotationInfo(Class cla){
            AnnotationClass annotationClass = (AnnotationClass) cla.getAnnotation(AnnotationClass.class);
            if(annotationClass!=null){
                System.out.println("deep=="+annotationClass.deep());
                System.out.println("height=="+annotationClass.height());
                System.out.println("shape=="+annotationClass.shape());
                System.out.println("width=="+annotationClass.width());
            }
        }
    

    相关文章

      网友评论

          本文标题:Java中的反射

          本文链接:https://www.haomeiwen.com/subject/jhjncrtx.html