给构造函数为private的类实例化,无视java安全机制
import java.lang.reflect.Field; import sun.misc.Unsafe; public class Test { public static void main(String[] args) throws Exception{ Field f1 = Unsafe.class.getDeclaredField("theUnsafe"); f1.setAccessible(true); Unsafe unsafe = (Unsafe) f1.get(null); User user = (User) unsafe.allocateInstance(User.class); Field f2 = user.getClass().getDeclaredField("name"); long momoryAddress = unsafe.objectFieldOffset(f2); //获取堆外内存地址 unsafe.putObject(user,unsafe.objectFieldOffset(f2), "xieyong"); System.out.println(unsafe.getObject(user, momoryAddress)); } static class User{ private User(){ } private String name; } }
原文地址:http://www.cnblogs.com/JimmyXie/p/3780285.html