Unsafe

Unsafe

首先unsafe 是不可以被实例化的,是内部的api 不允许外部直接调用

可能在以后的版本会被删除

如何创建一个unsafe类

通过反射进行创建一个类

1
2
3
4
5
6
7
8
9
10
try {
Constructor constructor = Unsafe.class.getDeclaredConstructor();
constructor.setAccessible(true);
Unsafe unsafe = (Unsafe) constructor.newInstance();
myUnsafe.unsafe = unsafe;
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InvocationTargetException | InstantiationException | IllegalAccessException e) {
throw new RuntimeException(e);
}

image-20250508195643316

无视构造函数构造类

使用unsafe.allocateInstance

假设一下的类不能被创建了

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package fun.au9u5t;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class User implements Serializable
{
public String name;
private int age;

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

public void Say(){
System.out.println(this.name+": My name is " + name + " and I am " + age + " years old.");
}

private void Say(String message ){
System.out.println(this.name+": "+message);
}

public void setName(String name){
this.name = name;
}

public String ToString(){
return this.name+": My name is " + name + " and I am " + age + " years old.";
}

// public static void main(String[] args) {
// User user = new User("august",99);
// // 序列化成文件
// String fileName= "user.ser";
// try (ObjectOutputStream oos= new ObjectOutputStream(new FileOutputStream(fileName))){
// oos.writeObject(user);
// }catch (IOException e){
// e.printStackTrace();
// }
// }
}

尝试直接创建对象

1
User user=(User) unsafe.allocateInstance(User.class);

image-20250508195958440


Unsafe
https://tsy244.github.io/2025/05/08/java安全/Unsafe/
Author
August Rosenberg
Posted on
May 8, 2025
Licensed under