枚举单例函数如何?(How does an enum singleton function?)

编程入门 行业动态 更新时间:2024-10-21 09:35:39
枚举单例函数如何?(How does an enum singleton function?)

以前,而不是使用枚举,我会做这样的事情:

public static ExampleClass instance; public ExampleClass(){ instance=this; } public static ExampleClass getInstance(){ return instance; }

然后有人告诉我一个枚举单例:

public enum Example{ INSTANCE; public static Example getInstance(){ return Example.INSTANCE; }

在第一个例子中,我必须实例化对象才能创建实例。 有了枚举,我不需要那样做......至少看起来是这样。 有人能解释这背后的原因吗?

Previously instead of using enums, I would do something like:

public static ExampleClass instance; public ExampleClass(){ instance=this; } public static ExampleClass getInstance(){ return instance; }

Then someone told me about a enum singleton:

public enum Example{ INSTANCE; public static Example getInstance(){ return Example.INSTANCE; }

In the first example I had to instantiate the object in order to create the instance. With an enum, I do not need to do that.. at least it appears. Can someone explain the reason behind this?

最满意答案

Java编译器负责将字段代码中的枚举字段创建为Java类的静态实例。 在这里(不是我的博客)很棒的博客文章和字节码在这里: http : //boyns.blogspot.com/2008/03/java-15-explained-enum.html

The Java compiler takes care of creating enum fields as static instances of a Java class in bytecode. Great blog post on it (not my blog) with bytecode here: http://boyns.blogspot.com/2008/03/java-15-explained-enum.html

更多推荐

本文发布于:2023-07-31 02:40:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1340523.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   enum   function   singleton

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!