Mr Dk.'s BlogMr Dk.'s Blog
  • 🦆 About Me
  • ⛏️ Technology Stack
  • 🔗 Links
  • 🗒️ About Blog
  • Algorithm
  • C++
  • Compiler
  • Cryptography
  • DevOps
  • Docker
  • Git
  • Java
  • Linux
  • MS Office
  • MySQL
  • Network
  • Operating System
  • Performance
  • PostgreSQL
  • Productivity
  • Solidity
  • Vue.js
  • Web
  • Wireless
  • 🐧 How Linux Works (notes)
  • 🐧 Linux Kernel Comments (notes)
  • 🐧 Linux Kernel Development (notes)
  • 🐤 μc/OS-II Source Code (notes)
  • ☕ Understanding the JVM (notes)
  • ⛸️ Redis Implementation (notes)
  • 🗜️ Understanding Nginx (notes)
  • ⚙️ Netty in Action (notes)
  • ☁️ Spring Microservices (notes)
  • ⚒️ The Annotated STL Sources (notes)
  • ☕ Java Development Kit 8
GitHub
  • 🦆 About Me
  • ⛏️ Technology Stack
  • 🔗 Links
  • 🗒️ About Blog
  • Algorithm
  • C++
  • Compiler
  • Cryptography
  • DevOps
  • Docker
  • Git
  • Java
  • Linux
  • MS Office
  • MySQL
  • Network
  • Operating System
  • Performance
  • PostgreSQL
  • Productivity
  • Solidity
  • Vue.js
  • Web
  • Wireless
  • 🐧 How Linux Works (notes)
  • 🐧 Linux Kernel Comments (notes)
  • 🐧 Linux Kernel Development (notes)
  • 🐤 μc/OS-II Source Code (notes)
  • ☕ Understanding the JVM (notes)
  • ⛸️ Redis Implementation (notes)
  • 🗜️ Understanding Nginx (notes)
  • ⚙️ Netty in Action (notes)
  • ☁️ Spring Microservices (notes)
  • ⚒️ The Annotated STL Sources (notes)
  • ☕ Java Development Kit 8
GitHub
  • 📝 Notes
    • Algorithm
      • Algorithm - Bloom Filter
      • Algorithm - Disjoint Set
      • Algorithm - Fast Power
      • Algorithm - KMP
      • Algorithm - Monotonic Stack
      • Algorithm - RB-Tree
      • Algorithm - Regular Expression
      • Algorithm - Sliding Window
      • Online Judge - I/O
    • C++
      • C++ - Const
      • C++ File I/O
      • C++ - Object Layout
      • C++ - Operator Overload
      • C++ - Polymorphism
      • C++ STL algorithm
      • C++ STL map
      • C++ STL multimap
      • C++ STL priority_queue
      • C++ STL set
      • C++ STL string
      • C++ STL unordered_map
      • C++ STL vector
      • C++ - Smart Pointer
      • C++ - Template & Genericity
    • Compiler
      • ANTLR - Basic
      • Compiler - LLVM Architecture
      • Compiler - Multi-version GCC
    • Cryptography
      • Cryptography - Certbot
      • Cryptography - Digital Signature & PKCS #7
      • Cryptography - GPG
      • Cryptography - JWT
      • Cryptography - Keystore & Certificates
      • Cryptography - OAuth 2.0
      • Cryptography - Java 实现对称与非对称加密算法
      • Cryptography - TLS
    • DevOps
      • DevOps - Travis CI
    • Docker
      • Docker - Image & Storage Management
      • Docker - Image
      • Docker - Libcontainer
      • Docker - Multi-Arch Image
      • Docker - Multi-Stage Build
      • Docker - Network
      • Docker - Orchestration & Deployment
      • Docker - Overview
      • Docker - Service Building
      • Docker - Volume & Network Usage
      • Docker - Volume
      • Linux - Control Group
      • Linux - Namespace
    • Git
      • Git - Branch & Merge
      • Git - Cached
      • Git - Cherry Pick
      • Git - Commit
      • Git - Patch
      • Git - Proxy
      • Git - Rebase
      • Git - Reset
      • Git - Stash
      • Git - Theme for Git-Bash
    • Java
      • JVM - Synchronized
      • JVM - Volatile
      • Java - Annotation 注解
      • Java - BIO & NIO
      • Java - Class Path
      • Java - Condition and LockSupport
      • Java - Current Timestamp
      • Java - Deep Copy
      • Java - 运行环境配置
      • Java - Equals
      • Java - Exporting JAR
      • Java - Javadoc
      • Java - Lock
      • Java - Maven 项目构建工具
      • Java - References
      • Java - Reflection Mechanism
      • Java - String Split
      • Java - Thread Pool
      • Java - Thread
      • Tomcat - Class Loader
      • Tomcat - Container
    • Linux
      • addr2line
      • cut
      • df
      • du
      • fallocate
      • find
      • fio
      • grep
      • groupadd
      • gzip
      • head / tail
      • hexdump
      • iostat
      • iotop
      • kill
      • ldd
      • lsof
      • ltrace / strace
      • mpstat
      • netstat
      • nm
      • pidstat
      • pmap
      • readlink
      • readlink
      • rpm2cpio / rpm2archive
      • sort
      • tee
      • uniq
      • useradd
      • usermod
      • watch
      • wc
      • which
      • xargs
    • MS Office
      • MS Office - Add-in Dev
      • MS Office - Application
    • MySQL
      • InnoDB - Architecture
      • InnoDB - Backup
      • InnoDB - Checkpoint
      • InnoDB - Critical Features
      • InnoDB - Files
      • InnoDB - Index
      • InnoDB - Insert Buffer
      • InnoDB - Lock
      • InnoDB - Partition Table
      • InnoDB - Table Storage
      • MySQL - Server Configuration
      • MySQL - Storage Engine
    • Network
      • Network - ARP
      • Network - FTP
      • Network - GitHub Accelerating
      • HTTP - Message Format
      • HTTP - POST 提交表单的两种方式
      • Network - Proxy Server
      • Network - SCP
      • Network - SSH
      • Network - TCP Congestion Control
      • Network - TCP Connection Management
      • Network - TCP Flow Control
      • Network - TCP Retransmission
      • Network - Traceroute
      • Network - V2Ray
      • Network - WebSocket
      • Network - Windows 10 Mail APP
      • Network - frp
    • Operating System
      • Linux - Kernel Compilation
      • Linux - Multi-OS
      • Linux - Mutex & Condition
      • Linux - Operations
      • Linux: Package Manager
      • Linux - Process Manipulation
      • Linux - User ID
      • Linux - Execve
      • OS - Compile and Link
      • OS - Dynamic Linking
      • OS - ELF
      • Linux - Image
      • OS - Loading
      • OS - Shared Library Organization
      • OS - Static Linking
      • Syzkaller - Architecture
      • Syzkaller - Description Syntax
      • Syzkaller - Usage
      • Ubuntu - Desktop Recover (Python)
      • WSL: CentOS 8
    • Performance
      • Linux Performance - Perf Event
      • Linux Performance - Perf Record
      • Linux Performance - Perf Report
      • Linux Performance - Flame Graphs
      • Linux Performance - Off CPU Analyze
    • PostgreSQL
      • PostgreSQL - ANALYZE
      • PostgreSQL - Atomics
      • PostgreSQL - CREATE INDEX CONCURRENTLY
      • PostgreSQL - COPY FROM
      • PostgreSQL - COPY TO
      • PostgreSQL - Executor: Append
      • PostgreSQL - Executor: Group
      • PostgreSQL - Executor: Limit
      • PostgreSQL - Executor: Material
      • PostgreSQL - Executor: Nest Loop Join
      • PostgreSQL - Executor: Result
      • PostgreSQL - Executor: Sequential Scan
      • PostgreSQL - Executor: Sort
      • PostgreSQL - Executor: Unique
      • PostgreSQL - FDW Asynchronous Execution
      • PostgreSQL - GUC
      • PostgreSQL - Locking
      • PostgreSQL - LWLock
      • PostgreSQL - Multi Insert
      • PostgreSQL - Plan Hint GUC
      • PostgreSQL - Process Activity
      • PostgreSQL - Query Execution
      • PostgreSQL - Spinlock
      • PostgreSQL - Storage Management
      • PostgreSQL - VFD
      • PostgreSQL - WAL Insert
      • PostgreSQL - WAL Prefetch
    • Productivity
      • LaTeX
      • Venn Diagram
      • VuePress
    • Solidity
      • Solidity - ABI Specification
      • Solidity - Contracts
      • Solidity - Expressions and Control Structures
      • Solidity - Layout and Structure
      • Solidity - Remix IDE
      • Solidity - Slither
      • Solidity - Types
      • Solidity - Units and Globally Available Variables
    • Vue.js
      • Vue.js - Environment Variable
    • Web
      • Web - CORS
      • Web - OpenAPI Specification
    • Wireless
      • Wireless - WEP Cracking by Aircrack-ng
      • Wireless - WPS Cracking by Reaver
      • Wireless - wifiphisher

Java - Reflection Mechanism

Created by : Mr Dk.

2018 / 09 / 22 21:15

Nanjing, Jiangsu, China


About

Reflection - 反射

通过 .class 文件动态加载类,而不用通过类对象,就能获取类的所有信息,包括 field、method、constructor 等。不用通过类对象,就能调用类的函数。在运行时判断任意一个对象所属的类。

Usage

  1. 获取 Class 对象
  2. 利用 Class 对象获取类信息 (域、函数、构造函数)
  3. 使用构造函数实例化对象 / 访问属性 / 调用函数

类装载过程

加载某个类的 .class 文件。JVM 在磁盘上寻找对应的 .class 文件,并载入 JVM 内存。JVM 自动创建一个 Class 对象,一个类只产生一个 Class 对象,其中存储与类有关的各种信息。

获取 Class 对象

class Base {

    // Fields
    private int a;
    private String b;

    // Getters & Setters for fields
    public void setA(int a) {
        this.a = a;
    }
    public int getA() {
        return a;
    }
    public void setB(String b) {
        this.b = b;
    }
    public String getB() {
        return b;
    }

    // Constructors
    public Base() {}
    public Base(int a) {this.a = a;}
    public Base(String b) {this.b = b;}
    public Base(int a, String b) {
        this.a = a;
        this.b = b;
    }

    // Methods
    public void Print(String msg) {
        System.out.println(msg);
    }
}
/**
 * 通过类获得 Class 对象
 */
Class clazz = Base.class;

/**
 * 通过类对象获得 Class 对象
 */
Base base = new Base();
Class clazz = base.getClass();

/**
 * 通过类全名(字符串)获得 Class 对象 - 最常用
 */
Class clazz = Class.forName("package.Base");

获取类信息

只能获取到当前类的信息,不能获取到父类的信息

  • 获取构造函数

    /**
     * 获取所有的 public Constructor
     */
    Constructor[] constructors = clazz.getConstructors();
    
    /**
     * 获取所有的 Constructor (包括 private、protected)
     */
    Constructor[] constructors = clazz.getConstructors();
    
    /**
     * 获取某个特定的 public Constructor
     * 参数为对应的 Class 对象
     */
    Constructor constructor = clazz.getConstructor(int.class, String.class);
    
    /**
     * 获取某个特定的 Constructor
     * 参数为对应的 Class 对象
     */
    Constructor constructor = clazz.getDeclaredConstructor(int.class, String.class);
    
  • 获取成员变量

    /**
     * 获取所有 field
     */
    Field[] fields = clazz.getDeclaredFields();
    
    /**
     * 获取所有的 public field
     */
    Field[] fields = clazz.getFields();
    
    /**
     * 获取某个特定 field
     */
    Field field = clazz.getDeclaredField("a");
    
    /**
     * 获取某个特定的 public field
     */
    Field field = clazz.getField("a");
    
  • 获取函数

    /**
     * 获取所有的 public method
     */
    Method[] methods = clazz.getMethods();
    
    /**
     * 获取所有的 method
     */
    Method[] methods = clazz.getDeclaredMethods();
    
    /**
     * 获取某个特定的 public method
     * 第一个参数为函数名,之后的参数为对应的参数列表的 class 对象
     */
    Method method = clazz.getMethod("Print", String.class);
    
    /**
     * 获取某个特定的 method
     * 第一个参数为函数名,之后的参数为对应的参数列表的 class 对象“
     */
    Method method = clazz.getDeclaredMethod("Print", String.class);
    

对类的一些操作

  • 实例化

    /**
     * 返回类型为 Object
     * 调用无参数的 Constructor(必须定义并实现!!!)
     */
    Object obj = clazz.newInstance();
    
    /**
     * 返回类型为 Object
     * 可以指定使用不同的构造函数
     */
    Constructor constructor = clazz.getConstructor(int.class, String.class);
    Object obj = constructor.newInstance(50, "Mr Dk.");
    
  • 访问属性

    Field field = clazz.getDeclaredField("a");
    field.setAccessible(true);    // 用于访问 private 变量,但不建议使用
    int a = field.getInt(obj);
    
  • 获取父类属性

    for (; !clazz.equals(Object.class); clazz = clazz.getSuperclass()) {
        // ...
        Field[] allFields = clazz.getDeclaredFields();
        // ...
    }
    
  • 调用函数

    Method method = clazz.getDeclaredMethod("Print", String.class);
    method.invoke(obj, "HelloWorld");
    

Pros and Cons

Pros

应用在那些需要 在运行时检测或修改程序行为 的程序中。

Cons

反射的效率比非反射低得多,所以避免在经常执行的代码中使用,避免在对性能要求较高的代码中使用。使用反射要求程序必须在一个没有安全限制的环境内运行,因为产生了内部暴露,允许一些正常情况下不被允许的操作:

  • 访问 private 属性
  • 访问 private 函数

反射可能导致一些副作用,如:

  • 代码功能上的错误
  • 降低可移植性
  • 破坏代码的抽象性
  • 不同运行平台上的行为差异

Edit this page on GitHub
Prev
Java - References
Next
Java - String Split