zoukankan      html  css  js  c++  java
  • Java基础三、反射

    57、什么是反射?

    反射是在运行状态中,对于任意一个类,都能知道这个类的所有属性和方法;对于任意一个对象,都能够调用它的任意一个方法和属性;这种动态获取的信息以及动态调用对象的方法的功能称为Java语言的反射机制。

    58、什么是Java序列化?什么情况下需要序列化?

    Java序列化是为了保存各种对象在内存中的状态,并且可以把保存的对象状态再读取出来。

    以下情况需要使用Java序列化

    1) 想把内存中的对象状态保存到一个文件中或者数据库中

    2) 想用套接字在网络上传输对象的时候

    3) 想通过RMI(远程方法调用)传输对象的时候。

    59、动态代理是什么? 有哪些应用?

    动态代理是运行时动态生成代理类。

    动态代理的应用: spirng aop, hiberanate数据查询,测试框架的后端mock,rpc, Java注解对象获取等。

    60. 怎么实现动态代理?

    JDK原生动态代理和cglib动态代理。 JDK原生动态代理是基于接口实现的,而cglib是基于当前继承当前类的子类实现的。

    二、其它

    1、反射的缺点

    性能第一  Performance Overhead

    Because reflection involves types that are dynamically resolved, certain Java virtual machine optimizations can not be performed. Consequently, reflective operations have slower performance than their non-reflective counterparts, and should be avoided in sections of code which are called frequently in performance-sensitive applications. 

    反射包括了一些动态类型,所以JVM无法对这些代码进行优化。因此,反射操作的效率要比那些非反射操作低得多。我们应该避免在经常被 执行的代码或对性能要求很高的程序中使用反射。

    安全限制  Security Restrictions

    Reflection requires a runtime permission which may not be present when running under a security manager. This is in an important consideration for code which has to run in a restricted security context, such as in an Applet. 

    使用反射技术要求程序必须在一个没有安全限制的环境中运行。如果一个程序必须在有安全限制的环境中运行,如Applet,那么这就是个问题了。

    内部暴露  Exposure of Internals

    Since reflection allows code to perform operations that would be illegal in non-reflective code, such as accessing  private fields and methods, the use of reflection can result in unexpected side-effects, which may render code dysfunctional and may destroy portability. Reflective code breaks abstractions and therefore may change behavior with upgrades of the platform. 

    由于反射允许代码执行一些在正常情况下不被允许的操作(比如访问私有的属性和方法),所以使用反射可能会导致意料之外的副作用--代码有功能上的错误,降低可移植性。反射代码破坏了抽象性,因此当平台发生改变的时候,代码的行为就有可能也随着变化。

  • 相关阅读:
    1、Jenkins的安装与简单配置
    2、jenkins+svn自动发布和回滚
    关于kafka生产者相关监控指标的理解(未解决)
    Zabbix中获取各用户告警媒介分钟级统计
    2-4、配置Filebeat使用logstash
    JS基础 浏览器弹出的三种提示框(提示信息框、确认框、输入文本框)
    C# winform 托盘控件的使用
    c# 将两个表的有效数据合到一个表中
    C# 认识 接口
    let 和 var 定义变量的区别
  • 原文地址:https://www.cnblogs.com/linlf03/p/10776992.html
Copyright © 2011-2022 走看看