上一篇 | 这是最后一篇日志下一篇
Java 订阅所有Java的日志

获取java对象地址的一个工具类

一个获取java对象地址的工具类:
程序代码 程序代码


import java.lang.reflect.Field;

import sun.misc.Unsafe;

public class Addresser {
    
    private static Unsafe unsafe;

    static
    {
        try
        {
            Field field = Unsafe.class.getDeclaredField("theUnsafe");
            field.setAccessible(true);
            unsafe = (Unsafe)field.get(null);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    public static long addressOf(Object o)
    throws Exception
    {
        Object[] array = new Object[] {o};

        long baseOffset = unsafe.arrayBaseOffset(Object[].class);
        int addressSize = unsafe.addressSize();
        long objectAddress;
        switch (addressSize)
        {
            case 4:
                objectAddress = unsafe.getInt(array, baseOffset);
                break;
            case 8:
                objectAddress = unsafe.getLong(array, baseOffset);
                break;
            default:
                throw new Error("unsupported address size: " + addressSize);
        }      

        return(objectAddress);
    }


    public static void main(String... args)
    throws Exception
    {  
        Object mine = "Hi there".toCharArray();
        Object another = "Hi there".toCharArray();
        long address = addressOf(mine);
        long addressAnother = addressOf(another);
        
        Object mine2 = mine;
        long addressMine2 = addressOf(mine);
        System.out.println("mine Addess: " + address);
        System.out.println("mine2 Addess: " + addressMine2);
        System.out.println("another Addess: " + addressAnother);
        //Verify address works - should see the characters in the array in the output
        printBytes(address, 27);

    }

    public static void printBytes(long objectAddress, int num)
    {
        for (long i = 0; i < num; i++)
        {
            int cur = unsafe.getByte(objectAddress + i);
            System.out.print((char)cur);
        }
        System.out.println();
    }

}


除非申明,文章均为一号门原创,转载请注明本文地址,谢谢!
文章来自: 本站原创
引用通告: 查看所有引用 | 我要引用此文章
Tags:
相关日志:
评论: 0 | 引用: 0 | 查看次数: -
发表评论
昵 称:
密 码: 游客发言不需要密码.
内 容:
验证码: 验证码
选 项:
虽然发表评论不用注册,但是为了保护您的发言权,建议您注册帐号.