We know that when the constructor of a class is set to private, it means that we cannot create the object directly by using the New keyword, and we can use Sun.misc.Unsafe to achieve the purpose of creating the object, which is Java's underlying operation-based API. You can directly perform underlying operations, such as obtaining an offset address for a property, or even loading the class file bytecode into memory directly, breaking through the Java Virtual machine sandbox limit.
1. Create a User.java with the following content:
Public class user{ private User () { System.out.println ("constructor User:") ); } }
2. Create Unsafetest
ImportJava.lang.reflect.Field;ImportSun.misc.Unsafe; Public classUnsafetest { Public Static voidMain (string[] args) {Try{ //using unsafe to construct an instanceField Field= Unsafe.class. Getdeclaredfield ("Theunsafe"); Field.setaccessible (true); unsafe unsafe= (Unsafe) field.get (NULL); User User= (user) unsafe.allocateinstance (user).class); SYSTEM.OUT.PRINTLN (user); }Catch(Exception e) {e.printstacktrace (); } } }
Output:
[Email protected]
Java Security Series-breaking private fabric limits