给构造函数为private的类实例化,无视java安全机制

作者:JimmyYong 和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

相关资料:

给构造函数为private的类实例化,无视java安全机制来源网络,如有侵权请告知,即处理!

编程Tags: