简体   繁体   English

仅具有静态方法的类-是否为Enum

[英]Class with only static methods - Enum or not

Time after time I have a situation where I have an utility class containing only static methods. 一次又一次,我遇到了一个只包含静态方法的实用程序类的情况。


The question is not about the fact of having such classes themselfes, so not a debate about utility classes. 问题不是关于自己拥有这样的类的事实,而是关于实用程序类的辩论。 We just assume that there is a use case where this class makes sense. 我们只是假设有一个用例,该类有意义。


Now I have seen different possibilities to prevent instantiation/extension: 现在,我看到了防止实例化/扩展的不同可能性:

  • a private constructor and final class 私有构造函数和最终类
  • using an enum instead of a class 使用枚举而不是类

What is the best practice here? 最佳做法是什么? Could you elaborate the benefits/drawbacks of the two possibilities? 您能否详细说明这两种可能性的优点/缺点?


Personally I prefer the enum solution, as it completely prevents instantiation and extension out of the box, but maybe I am wrong. 就我个人而言,我更喜欢枚举解决方案,因为它完全防止了开箱即用的实例化和扩展,但是也许我错了。

Thank you already! 已经谢谢你了!

I would prefer the former. 我希望前者。

First of all, using a final class with a private constructor is what I do all the time when I'm writing a utility class. 首先,在编写实用程序类时,我一直都在使用带有私有构造函数的最终类。 I have never even thought of using enums. 我什至从未想到使用枚举。

The main reason for not using an enum is that you can still technically write something like this: 不使用枚举的主要原因是,您仍然可以在技术上编写如下代码:

MyEnum var = MyEnum.valueOf("Hello");

and the compiler doesn't say a thing about it, not even IntelliJ IDEA! 而且编译器也没说什么,甚至IntelliJ IDEA也没说!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM