准备
- Reflection源码阅读
- JNI机制
功能描述
Unsafe类提供了一些底层的, 相对不安全的操作, 可直接操作内存.
基本类图
成员变量
命名 | modifiers | 类型 | 说明 |
---|---|---|---|
theUnsafe | private static final | unsafe | Unsafe类的实例 ( 单例模式 ) |
成员方法
方法名称 | modifier | 返回值 | 方法入参 | 说明 |
---|---|---|---|---|
getUnsafe | public static | Unsafe | 获取theUnsafe变量, 如果是不被信任的代码, 则会抛出不安全的异常信息.(信任的代码: 通过Bootstrap ClassLoader或者Ext ClassLoader加载的类) | |
getInt | public native | int | Object o, long offset | 从入参数对象o中读取内存地址为offset的int型值 |
putInt | public native | void | Object o, long offset, int x | 给对象o赋值x,内存地址为offset的变量 |
getxxx | ... | |||
putxxx | ... | |||
getAddress | public native | long | long address | 返回指定address地址的一个指针 |
putAddress | public native | void | long address, long x | 保存指针x到指定address地址 |
... |
总结
-
Unsafe是一个典型的饿汉式单例模式, 私有化构造函数,并提供实例theUnsafe, 以及提供静态方法getUnsafe .
注意⚠️: Unsafe的所有操作都必须是可信任的类.