Home >Java >javaTutorial >How to Determine the Size of an Object in Java?

How to Determine the Size of an Object in Java?

DDD
DDDOriginal
2024-11-05 07:07:01988browse

How to Determine the Size of an Object in Java?

Determine Object Size in Java

Despite the prevalence of the sizeOf() method in languages like C/C , Java lacks a direct equivalent for calculating the memory footprint of an object. This article explores alternative approaches to address this need.

Utilizing Instrumentation Package

The Java Instrumentation API provides the getObjectSize() method, which offers an approximation of object size specific to its implementation. An example usage:

<code class="java">import java.lang.instrument.Instrumentation;

public class ObjectSizeFetcher {
    private static Instrumentation instrumentation;

    public static void premain(String args, Instrumentation inst) {
        instrumentation = inst;
    }

    public static long getObjectSize(Object o) {
        return instrumentation.getObjectSize(o);
    }
}</code>

To use this method, specify the following in your manifest file:

<code class="xml"><instrumentation>
  <main class="ObjectSizeFetcher">
    <option name="tools" value="all"/>
  </main>
</instrumentation></code>

From your application code, call getObjectSize() as below:

<code class="java">public class C {
    private int x;
    private int y;

    public static void main(String[] args) {
        System.out.println(ObjectSizeFetcher.getObjectSize(new C()));
    }
}</code>

The above is the detailed content of How to Determine the Size of an Object in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn