zoukankan      html  css  js  c++  java
  • 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;
        }
    }
  • 相关阅读:
    analysis of algorithms
    Measurement of Reflected Radiation
    lecture 5
    lecture 3
    字符串
    Emission of Radiation辐射发射
    Electromagnetic Radiation(EMR) 电磁辐射
    Linux FTP服务器-VSFTPD虚拟用户配置
    jenkins notes
    python nose使用记录
  • 原文地址:https://www.cnblogs.com/stono/p/8268492.html
Copyright © 2011-2022 走看看