Java中是否有类似sizeof的方法? [英] Is there any sizeof-like method in Java?

查看:512
本文介绍了Java中是否有类似sizeof的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java中是否有任何内置方法可以找到任何数据类型的大小?
有没有找到尺寸的方法?

Is there any built-in method in Java to find the size of any datatype? Is there any way to find size?

推荐答案

没有。标准Java SE类库中没有这样的方法。

No. There is no such method in the standard Java SE class library.

设计者的观点是Java中不需要它,因为该语言不再需要应用程序 1 了解需要为原始值,对象或具有给定数量元素的数组保留多少空间。

The designers' view is that it is not needed in Java, since the language removes the need for an application1 to know about how much space needs to be reserved for a primitive value, an object or an array with a given number of elements.

您可能认为sizeof运算符对于需要了解其数据结构占用空间的人员非常有用。但是,您也可以使用Java内存分析器简单可靠地获取此信息,因此不需要sizeof方法。

You might think that a sizeof operator would be useful for people that need to know how much space their data structures take. However you can also get this information and more, simply and reliably using a Java memory profiler, so there is no need for a sizeof method.

以前的评论者指出 sizeof(someType) 4 更具可读性。如果您接受该可读性论证,那么补救措施就掌握在您手中。只需定义一个这样的类......

Previous commenters made the point that sizeof(someType) would be more readable than 4. If you accept that readability argument, then the remedy is in your hands. Simply define a class like this ...

public class PrimitiveSizes {
    public static int sizeof(byte b) { return 1; } 
    public static int sizeof(short s) { return 2; }
    // etcetera
}

...并静态导入它。 ..

... and statically import it ...

import static PrimitiveSizes.*;

或定义一些命名常量;例如。

Or define some named constants; e.g.

public static final int SIZE_OF_INT = 4;

或(Java 8及更高版本)使用 Integer.BYTES 常量,依此类推。

Or (Java 8 and later) use the Integer.BYTES constant, and so on.

为什么Java设计人员没有在标准库中实现这一点?我的猜测是:

Why haven't the Java designers implemented this in standard libraries? My guess is that:


  • 他们认为没有必要,

  • 他们并不认为有足够的需求,

  • 他们认为这不值得付出努力。

还有一个问题是,下一个需求将是 sizeof(Object o)方法,这种方法充满了技术难题。

There is also the issue that the next demand would be for a sizeof(Object o) method, which is fraught with technical difficulties.

上面的关键词是他们!

The key word in the above is "they"!

您或我对此的看法无关紧要。通过扩展,在评论中讨论这个主题是没有实际意义的。请不要。

1 - 程序员可能需要知道为了设计节省空间的数据结构。但是,我无法想象为什么在运行时通过方法调用在应用程序代码中需要这些信息。

这篇关于Java中是否有类似sizeof的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆