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

How to Determine the Size of an Object in Java?

DDD
Release: 2024-11-05 07:07:01
Original
955 people have browsed it

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template