Loading

sun.misc.unsafe类的使用

sun.misc.unsafe类的使用

学习了:http://blog.csdn.net/fenglibing/article/details/17138079

 真的可以创建private的实例:

package com.stono.test;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import sun.misc.Unsafe;

public class UnsafeTest {
    public static void main(String[] args) throws Exception{
        Field f = Unsafe.class.getDeclaredField("theUnsafe");
        f.setAccessible(true);
        Unsafe unsafe = (Unsafe)f.get(null);
        
        Player p = (Player)unsafe.allocateInstance(Player.class); // 这个猛,都不需要经过构造函数
        System.out.println(p.getAge());
        p.setAge(45);
        System.out.println(p.getAge());
        
        
        Constructor<Player> constructor = Player.class.getDeclaredConstructor();
        constructor.setAccessible(true);
        Player s2 = constructor.newInstance(); // 通过反射可以创建对象,但是必须经过构造函数
        System.out.println("reflect"+s2.getAge());
    }
}
class Player{
    private int age = 12;
    private Player(){
        this.age = 50;
    }
    public int getAge(){
        return this.age;
    }
    public void setAge(int age){
        this.age = age;
    }
}

 

posted @ 2018-01-11 15:07  stono  阅读(175)  评论(0编辑  收藏  举报