反射及动态代理

反射

        定义:

                反射允许对封装类的字段,方法和构造 函数的信息进行编程访问

                

                                                                        图来自黑马程序员 

        获取class对象的三种方式:

                1)Class.forName("全类名")

                2)类名.class

                3) 对象.getClass()

                

                                                                         图来自黑马程序员  

                

package com.lazyGirl.reflectdemo;

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


        //最常见
        Class clazz = Class.forName("com.lazyGirl.reflectdemo.Student");
        System.out.println(clazz);

        Class clazz2 = Student.class;
        System.out.println(clazz2);

        System.out.println(clazz == clazz2);

        Student student = new Student();
        Class clazz3 = student.getClass();
        System.out.println(clazz3);
        System.out.println(clazz == clazz3);
    }
}

        输出:

         

 获取构造方法:

                                                                     图来自黑马程序员  

package com.lazyGirl.reflectdemo.demo1;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Parameter;

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


        Class clazz = Class.forName("com.lazyGirl.reflectdemo.demo1.Student");
        Constructor[] cons = clazz.getConstructors();
        for (Constructor c : cons) {
            System.out.println(c);
        }

        System.out.println();

        Constructor[] cons1 = clazz.getDeclaredConstructors();
        for (Constructor c : cons1) {
            System.out.println(c);
        }
        System.out.println();

        Constructor cons2 = clazz.getDeclaredConstructor();
        System.out.println(cons2);
        System.out.println();

        Constructor cons3 = clazz.getDeclaredConstructor(String.class);
        System.out.println(cons3);
        System.out.println();


        Constructor cons4 = clazz.getDeclaredConstructor(int.class);
        System.out.println(cons4);
        System.out.println();

        Constructor cons5 = clazz.getDeclaredConstructor(String.class, int.class);
        System.out.println(cons5);

        int modifiers = cons5.getModifiers();
        System.out.println(modifiers);
        System.out.println();

        Parameter[] parameters = cons5.getParameters();
        for (Parameter p : parameters) {
            System.out.println(p);
        }
        
        cons5.setAccessible(true);
        Student stu = (Student) cons5.newInstance("hhh",16);
        System.out.println(stu);

    }
}

        输出:

         

 获取成员变量:

                                                                 图来自黑马程序员  

package com.lazyGirl.reflectdemo.demo2;

import java.lang.reflect.Field;

public class Demo {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException {

        Class clazz = Class.forName("com.lazyGirl.reflectdemo.demo2.Student");

        Field[] fields = clazz.getFields();
        for (Field field : fields) {
            System.out.println(field.getName());
        }
        System.out.println();


        Field[] declaredFields = clazz.getDeclaredFields();
        for (Field field : declaredFields) {
            System.out.println(field.getName());
        }
        System.out.println();

        Field gender = clazz.getField("gender");
        System.out.println(gender);
        System.out.println();

        Field declaredName = clazz.getDeclaredField("name");
        System.out.println(declaredName);
        System.out.println();

        int modifiers = declaredName.getModifiers();
        System.out.println(modifiers);

        String name = declaredName.getName();
        System.out.println(name);
        System.out.println();

        Class<?> type = declaredName.getType();
        System.out.println(type);

        Student student = new Student("hhh",16,"女");
        declaredName.setAccessible(true);
        Object value = declaredName.get(student);
        System.out.println(value);
        declaredName.set(student,"hhhh");
        System.out.println(student);

    }
}

输出:

获取成员方法:

                                                         图来自黑马程序员 

package com.lazyGirl.reflectdemo.demo3;

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

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

        Class clazz = Class.forName("com.lazyGirl.reflectdemo.demo3.Student");

        //包含父类的方法
//        Method[] methods = clazz.getMethods();

        //不能获取父类方法,但是可以访问私有方法
        Method[] methods = clazz.getDeclaredMethods();
        for (Method method : methods) {
            System.out.println(method);
        }

        Method method = clazz.getMethod("eat", String.class);
        System.out.println(method);

        int modifiers = method.getModifiers();
        System.out.println(modifiers);

        String name = method.getName();
        System.out.println(name);

        Parameter[] parameters = method.getParameters();
        for (Parameter parameter : parameters) {
            System.out.println(parameter);
        }

        Class[] exceptions = method.getExceptionTypes();
        for (Class exception : exceptions) {
            System.out.println(exception);
        }

        Student student = new Student();
        method.invoke(student,"cake");
    }
}

Student类:

package com.lazyGirl.reflectdemo.demo3;

public class Student {
    private String name;
    private int age;

    public Student() {
    }

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

    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 void sleep(){
        System.out.println("sleep");
    }

    public void eat(String food) throws InterruptedException,ClassCastException{
        System.out.println("eat " + food);
    }

    public void eat(String food, int time){
        System.out.println("eat " + food + " " + time);
    }

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

输出:

作用:

        获取一个类里面所有的信息,获取到了之后,再执行其他业务逻辑

        结合配置文件,动态的创建对象并调用方法

        

package com.lazyGirl.reflectdemo.demo5;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Properties;

public class Test {
    public static void main(String[] args) throws IOException, ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        Properties prop = new Properties();
        FileInputStream fis = new FileInputStream("pro.properties");
        prop.load(fis);

        fis.close();
        System.out.println(prop);

        String classname = (String) prop.get("classname");
        String methdName = (String) prop.get("method");
        System.out.println(classname);
        System.out.println(methdName);

        Class clazz = Class.forName(classname);
        Constructor constructor = clazz.getConstructor();
        Object o = constructor.newInstance();
        System.out.println(o);

        Method method = clazz.getDeclaredMethod(methdName);
        method.setAccessible(true);
        method.invoke(o);

    }
}

        properties文件:

classname=com.lazyGirl.reflectdemo.demo5.Student
method=study

        输出:

 

 动态代理:

        无侵入式的给代码增加额外的功能

        程序为什么需要代理:对象身上干的事太多,可以通过代理来转移部分职业

        对象有什么方法想被代理,代理就一定要有对应的方法

        java通过接口保证对象和代理

        格式:

        

                        图来自黑马程序员

                

        

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/745223.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

前端JS必用工具【js-tool-big-box】学习,数值型数组的正向排序和倒向排序

这一小节&#xff0c;我们说一下前端 js-tool-big-box 这个工具库&#xff0c;添加的数值型数组的正向排序和倒向排序。 以前呢&#xff0c;我们的数组需要排序的时候&#xff0c;都是在项目的utils目录里&#xff0c;写一段公共方法&#xff0c;弄个冒泡排序啦&#xff0c;弄…

JNI详解

JNI简介 Java是跨平台的语言&#xff0c;但在有的时候仍需要调用本地代码&#xff08;这些代码通常由C/C编写的&#xff09;。 Sun公司提供的JNI是Java平台的一个功能强大的接口&#xff0c;JNI接口提供了Java与操作系统本地代码互相调用的功能。 Java调C 1&#xff09;使用…

Spring Boot 学习第八天:AOP代理机制对性能的影响

1 概述 在讨论动态代理机制时&#xff0c;一个不可避免的话题是性能。无论采用JDK动态代理还是CGLIB动态代理&#xff0c;本质上都是在原有目标对象上进行了封装和转换&#xff0c;这个过程需要消耗资源和性能。而JDK和CGLIB动态代理的内部实现过程本身也存在很大差异。下面将讨…

VMware vSphere 8.0 Update 3 发布下载 - 企业级工作负载平台

VMware vSphere 8.0 Update 3 发布下载 - 企业级工作负载平台 vSphere 8.0U3 | ESXi 8.0U3 & vCenter Server 8.0U3 请访问原文链接&#xff1a;https://sysin.org/blog/vmware-vsphere-8-u3/&#xff0c;查看最新版。原创作品&#xff0c;转载请保留出处。 作者主页&am…

Java面试八股之JVM内存溢出的原因及解决方案

JVM内存溢出的原因及解决方案 JVM内存溢出&#xff08;Out Of Memory&#xff0c;OOM&#xff09;通常是由于程序运行过程中内存使用不当造成的&#xff0c;常见原因及相应的解决方案如下&#xff1a; 原因及解决方案 内存中加载的数据量过大 原因&#xff1a;一次性从数据…

运维入门技术——监控的三个维度(非常详细)零基础收藏这一篇就够了_监控维度怎么区分

一个好的监控系统最后要做到的形态:实现Metrics、Tracing、Logging的融合。监控的三个维度也就是Metrics、Tracing、Logging。 Metrics Metrics也就是我们常说的指标。 首先它的典型特征就是可聚合(aggregatable).什么是可聚合的呢,简单讲可聚合就是一种基本单位可以在一种维…

Verilog刷题笔记48——FSM1型异步复位

题目: 解题&#xff1a; module top_module(input clk,input areset, // Asynchronous reset to state Binput in,output out);// parameter A0, B1; reg state, next_state;always (*) begin // This is a combinational always block// State transition logiccase(…

加拿大魁北克IT人士的就业分析

魁北克省作为加拿大东部的一个重要省份&#xff0c;近年来在IT行业的就业市场上展现出了强劲的增长势头。随着数字化转型的加速&#xff0c;魁北克对IT专业人士的需求日益增加&#xff0c;特别是在软件开发、网络安全、数据分析和人工智能等领域。 热门职位方面&#xff0c;软…

禹晶、肖创柏、廖庆敏《数字图像处理(面向新工科的电工电子信息基础课程系列教材)》Chapter 9插图

禹晶、肖创柏、廖庆敏《数字图像处理&#xff08;面向新工科的电工电子信息基础课程系列教材&#xff09;》 Chapter 9插图

201.回溯算法:全排列(力扣)

class Solution { public:vector<int> res; // 用于存储当前排列组合vector<vector<int>> result; // 用于存储所有的排列组合void backtracing(vector<int>& nums, vector<bool>& used) {// 如果当前排列组合的长度等于 nums 的长度&am…

用 Rust 实现一个替代 WebSocket 的协议

很久之前我就对websocket颇有微词&#xff0c;它的确满足了很多情境下的需求&#xff0c;但是仍然有不少问题。对我来说&#xff0c;最大的一个问题是websocket的数据是明文传输的&#xff0c;这使得websocket的数据很容易遭到劫持和攻击。同时&#xff0c;WebSocket继承自HTTP…

【操作系统】操作系统发展简史

目录 1.前言 2.第一代&#xff08;1945~1955&#xff09;&#xff1a;真空管和穿孔卡片 3.第二代&#xff08;1955~1965&#xff09;&#xff1a;晶体管和批处理系统 4.第三代&#xff08;1965~1980&#xff09;&#xff1a;集成电路和多道程序设计 5.第四代&#xff08;1…

关于VMware遇到的一些问题

问题一&#xff1a;打不开磁盘…或它所依赖的某个快照磁盘&#xff0c;开启模块DiskEarly的操作失败&#xff0c;未能启动虚拟机 解决方法&#xff1a; 首先将centos 7关机&#xff0c;然后把快照1删掉 然后打开虚拟机所在目录&#xff0c;把提示的000001.vmdk全部删除&…

本地读取classNames txt文件

通过本地读取classNames,来减少程序修改代码,提高了程序的拓展性和自定义化。 步骤: 1、输入本地路径,分割字符串。 2、将className按顺序放入vector容器中。 3、将vector赋值给classNmaes;获取classNames.size(),赋值给CLASSES;这样,类别个数和类别都已经赋值完成。…

大厂面试官问我:Redis内存淘汰,LRU维护整个队列吗?【后端八股文四:Redis内存淘汰策略八股文合集】

往期内容&#xff1a; 大厂面试官问我&#xff1a;Redis处理点赞&#xff0c;如果瞬时涌入大量用户点赞&#xff08;千万级&#xff09;&#xff0c;应当如何进行处理&#xff1f;【后端八股文一&#xff1a;Redis点赞八股文合集】-CSDN博客 大厂面试官问我&#xff1a;布隆过滤…

vue3 Cesium 离线地图

1、vite-plugin-cesium 是一个专门为 Vite 构建工具定制的插件&#xff0c;用于在 Vite 项目中轻松使用 Cesium 库。它简化了在 Vite 项目中集成 Cesium 的过程。 npm i cesium vite-plugin-cesium vite -D 2、配置vite.config.js import cesium from vite-plugin-cesiumexp…

监测与管理:钢筋计在工程项目中的应用

在现代工程建设中&#xff0c;特别是大型长期工程项目&#xff0c;对结构安全性的监测与管理至关重要。钢筋计作为一种重要的监测工具&#xff0c;在工程项目中发挥着不可替代的作用。本文将探讨钢筋计在长期工程项目中的应用&#xff0c;包括安装方法、数据监测与分析以及实际…

“基于下垂的多电源分布式控制系统设计”,高分资源,匠心制作,查重5%,下载可用。强烈推荐!!!

“基于下垂的多电源分布式控制系统设计”&#xff0c;高分资源&#xff0c;匠心制作&#xff0c;查重5%&#xff0c;下载可用。强烈推荐&#xff01;&#xff01;&#xff01; 摘要 社会的进步与发展&#xff0c;人们对于能源的需求和依赖越来越大。与此同时&#xff0c;国家…

通达信擒牛亮剑出击抄底主升浪指标公式源码

通达信擒牛亮剑出击抄底主升浪指标公式源码&#xff1a; ABC1:(CLOSE-REF(CLOSE,1))/REF(CLOSE,1)*100; ABC2:IF(CLOSE>OPEN,CLOSE,OPEN); ABC3:IF(CLOSE>OPEN,OPEN,CLOSE); ABC4:LLV(ABC2,4); ABC5:HHV(ABC3,4); ABC6:ABC2>ABC4 AND ABC3<ABC4 AND ABC2>ABC5 …

【unity实战】制作unity数据保存和加载系统——大型游戏存储的最优解

最终效果 文章目录 最终效果前言存储位置信息存储更多数据存储场景信息持久化存储数据 前言 前面写过小型游戏存储功能&#xff1a; 【unity实战】制作unity数据保存和加载系统——小型游戏存储的最优解&#xff08;包含数据安全处理方案的加密解密&#xff09; 这次做一个针…
最新文章