##maven
com.carrotsearch
java-sizeof
0.0.3
##util
public class SizeOfUtil {
public static enum SizeEnum {
B {
@Override
public double getFromByteSize(long byteSize) {
return byteSize;
}
},K {
@Override
public double getFromByteSize(long byteSize) {
return byteSize*1.0/1024;
}
},M {
@Override
public double getFromByteSize(long byteSize) {
return byteSize*1.0/1024/1024;
}
},G {
@Override
public double getFromByteSize(long byteSize) {
return byteSize*1.0/1024/1024/1024;
}
};
public abstract double getFromByteSize(long byteSize);
}
/**
* 默认
* 返回bytes
* @param o
* @return
*/
public static double getObjectSize(Object o,SizeEnum sizeEnum){
long byteSize = 0;
if(o instanceof Collection>){
byteSize = RamUsageEstimator.sizeOfAll(o);
}else{
byteSize = RamUsageEstimator.sizeOf(o);
}
return sizeEnum.getFromByteSize(byteSize);
}
}
##使用
System.out.println(SizeOfUtil.getObjectSize(map, SizeOfUtil.SizeEnum.K));