JAVA中求解对象所占字节大小

该类为cache4j缓存框架中的工具类方法,该方法实现了两个接口

接口1:计算对象在内存中所占字节数

接口2:复制对象,实现深度克隆效果,实现原理为先序列化对象,然后在反序列化对象;返回一个新的对象,达到克隆效果

 

package net.sf.cache4j.impl;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
/**
 * 
 * @version $Revision: 1.0 $ $Date:$
 * @author Yuriy Stepovoy. <ahref="mailto:stepovoy@gmail.com">stepovoy@gmail.com</a>
 **/
public class Utils {
    /**
     * 计算一个对象所占字节数
     * @param o对象,该对象必须继承Serializable接口即可序列化
     * @return
     * @throws IOException
     */
 public static int size(final Object o) throws IOException {
  if (o == null) {
   return 0;
  }
  ByteArrayOutputStream buf = new ByteArrayOutputStream(4096);
  ObjectOutputStream out = new ObjectOutputStream(buf);
  out.writeObject(o);
  out.flush();
  buf.close();
  return buf.size();
 }
    /**
     * 赋值对象,返回对象的引用,如果参数o为符合对象,则内部每一个对象必须可序列化
     * @param o对象,该对象必须继承Serializable接口即可序列化
     * @return
     * @throws IOException
     * @throws ClassNotFoundException
     */
 public static Object copy(final Object o) throws IOException,
   ClassNotFoundException {
  if (o == null) {
   return null;
  }
  ByteArrayOutputStream outbuf = new ByteArrayOutputStream(4096);
  ObjectOutput out = new ObjectOutputStream(outbuf);
  out.writeObject(o);
  out.flush();
  outbuf.close();
  ByteArrayInputStream inbuf = new ByteArrayInputStream(outbuf.toByteArray());
  ObjectInput in = new ObjectInputStream(inbuf);
  return in.readObject();
 }
}


例如:对象SMatrix

首先在定义类SMatrix时,必须为

public class SMatrix implements Serializable{
//***
}



一定要注意的一个问题是:所计算的对象必须要实现implements Serializable

原文地址:https://www.cnblogs.com/wenbaoli/p/5655744.html