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; } }