⬆️ ⬇️

Enum-Almighty

Introductory



Very often, we use tools strictly according to purpose, barring ourselves from taking a step left or right. But what if we forget a little? What if we look at things we are used to from a different angle? This article summarizes the use of enumerations and conducted a small experiment on them. Sarcasm, humor and some philosophy questions. Who cares, welcome under cat.



Warning



In this article you will not find for yourself new technical knowledge, revelations, and if you crave them, then feel free to proceed to the next article. Nevertheless, there is something to be surprised at and something to think about. Technical humor and philosophical thoughts between the lines.



No story told ...



Once a developer gets to the place where fate is decided. Time later, an image appears in front of him and asks:

- Who are you?

- I, the developer, call Ivan , - but to myself: I stuck it in.

Voice again:

- Want to go there? . A look at the door, behind which paradise.

- Yeah , - timidly Ivan.

- What are you telling me? - asks the voice.

A little thought, Ivan begins to say:

- There is a java Enum-Almighty.

- How so, Almighty? - interrupts the voice with indignation. - This is only a listing!



public enum JavaLanguage { JAVA("Forever"), SCALA("Next generation") {}, KOTLIN("Future") {}; private final String claim; JavaLanguage(String claim) { this.claim = claim; } public String getClaim() { return claim; } } 


- Yeah , - says the developer, But not only.

- Prove it!

- Enum like nails, scrap mogot.

')

 public enum LanguageUtils { ; /** java-doc */ LanguageUtils() { throw new IllegalStateException("  "); } /** java-doc */ public static String[] getKeyWords(String languageName) { if (languageName != null) { //    return loadFromResource(languageName + "/keywords.dat"); } throw new IllegalStateException("  "); } /** java-doc */ private static synchronized String[] loadFromResource(String resourceName) { String[] items = null; //    return items; } /**     */ } 


- In so miracles, but ... He has no heir!

- And this is how to look. And who is considered the Heir? Scala? Kotlin?

- Give an example, without waiting for the developer to complete your question



  //  JavaLanguage.java  public static void main(String[] args) { // it's true if (JAVA.getClass() == SCALA.getClass().getSuperclass()) { System.out.println("  !"); } // it's true if (JAVA.getClass() == KOTLIN.getClass().getSuperclass()) { System.out.println("  !"); } } 


- Yeah, you guys are interesting, progers - already smiling, says the Voice, - But there will be a little

Having scratched his turnip, Ivan continued:

- Enum, we have a factory!

- No, it was already.

I had to get Ivan the last trump card:

- Enum-Singleton, for sure!

Choose your
Are you for Java?
 public enum Highlander { JAVA; Highlander() { if (ordinal() != 0) { throw new IllegalStateException("     "); } init(); } private void init() { //  ! } /** java-doc */ public String getOwner(String index) { //   return " , Sun Microsystems"; } } 


Are you for Scala?
 public enum Highlander { SCALA {}; Highlander() { if (ordinal() != 0) { throw new IllegalStateException("     "); } init(); } private void init() { //  ! } /** java-doc */ public String getOwner(String index) { //   return " ,    "; } } 


Are you for Kotlin?
 public enum Highlander { KOTLIN {}; Highlander() { if (ordinal() != 0) { throw new IllegalStateException("     "); } init(); } private void init() { //  ! } /** java-doc */ public String getOwner(String index) { //   return " , JetBrains"; } } 




- Joshua Bloch says * that this is the best implementation of Singleton.

- Well, what about you?

- What about me? This, this is a singleton factory , for storing one single item, titling bang ...



 Highlander.valueOf("JAVA"); 
This is the point to access the array to store a single element, to beat bash ...



 Highlander.values()[0]; 


This is the heir of the class ... , - Ivan wanted to continue, but was pleasantly surprised:

- Come on in ...



Few conclusions



In total, it turns out that enum can be endowed with the following qualities and properties, depending on the point of view:





Experiment



I decided to understand how much you can generate the elements of enumerations. My own answer and reality are so diverged that I doubted my knowledge. Before you look below, try to answer yourself. Simplify, say at least the order? Here is the code I used to generate the enumeration class (on a quick hand):



Code-generating enum?
 package com.enums; import java.io.*; public class EnumGeneratorShort implements Closeable { private BufferedWriter writer; public EnumGeneratorShort(File outputFile) throws IOException { writer = new BufferedWriter(new FileWriter(outputFile)); } void append(String line) throws IOException { writer.append(line); } void appendLine(String line) throws IOException { writer.append(line).append("\n"); } @Override public void close() throws IOException { if (writer != null) { writer.close(); } } /**   enum*/ private static final int ENUM_COUNT = XXXX; //  XXXX -  private static final char[] ALPHABET = new char[] { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'}; public static void main(String[] args) throws IOException { System.out.println("Start generation"); File outputFile = new File("src/main/java/com/enums/BigEnumShort.java"); try (EnumGeneratorShort enumGen = new EnumGeneratorShort(outputFile)) { enumGen.appendLine("package com.enums;"); enumGen.appendLine(""); enumGen.appendLine("public enum BigEnumShort {"); enumGen.append("A"); int index = 1; for (; index < ENUM_COUNT; index++) { enumGen.appendLine(","); String name = getName(index, ""); if ("if".equals(name) || "do".equals(name)) { name = getName(++index, ""); } enumGen.append(name); } enumGen.appendLine(";"); enumGen.appendLine(""); enumGen.appendLine(" public static void main(String[] args) {"); enumGen.appendLine(" System.out.println(\"Find enum \" + BigEnumShort.valueOf(\"B\"));"); enumGen.appendLine(" }"); enumGen.appendLine("}"); System.out.println("End generation. Total " + index); } } public static String getName(int index, String before) { if (index < ALPHABET.length) { return before + ALPHABET[index]; } int tail = index / ALPHABET.length; int current = index % ALPHABET.length; return getName(tail, before + ALPHABET[current]); } } 


Have you already guessed? So, on Semerochka I managed to generate a total of 2,746 enumeration elements. And then this:



Error_3
Total 5000

[ERROR] Failed to execute goal org.apache.maven.plugins: maven-compiler-plugin: 3.1: compile (default-compile) on project bigenum: Compilation failure

[ERROR] /home/XXX/temp/BigEnum/bigenum/src/main/java/com/enums/BigEnumShort.java:[4,1] code too large



But, since I rolled my lip into 4 floors, at first I received the following error:



Error_1
Total 134217727

Compiling 1 source file to / home / XXX / temp / BigEnum / bigenum / target / classes

An exception has occurred in the compiler (1.7.0_51). Please check the Bug Parade for duplicates for a bug at the Java Developer Connection (http://java.sun.com/webapps/bugreport). Include your program. Thank you.

java.lang.IllegalArgumentException



And then, twisting it a little, like this:



Error_2
Total 8388607

ERROR] Failed to execute goal org.apache.maven.plugins: maven-compiler-plugin: 3.1: compile (default-compile) on project bigenum: Compilation failure: Compilation failure:

[ERROR] /home/XXX/temp/BigEnum/bigenum/src/main/java/com/enums/BigEnumShort.java:[4,1] code too large

[ERROR] /home/XXX/temp/BigEnum/bigenum/src/main/java/com/enums/BigEnumShort.java:[3,8] too many constants



I was also wondering how such an enumeration can digest known decompilers. Total for the subjective assessment of expectations:

A placeDecompilerResult
onefernflower.jarOK
2jadOk
3procyonWaited
fourcfr_0_115.jarNot wait


Thank you for attention.



Sources and Inspirers



Effective Java, 2nd Edition, by Joshua Bloch *

Wikipedia

Right singleton in java

Comment by apanasevich

Comment by Sirikid

Source: https://habr.com/ru/post/321152/



All Articles