Enum-Almighty
Introductory
Very often, we use tools strictly for their intended purpose, forbidding ourselves to take a step left or right. But what if we are a little 'forgotten'? What if we look at familiar things from a different angle? This article has collected approaches to using enumerations and conducted a small experiment on them. Sarcasm, humor and some philosophical questions. Who cares, welcome to cat.
Warning
In this article you will not find for yourself new technical knowledge, revelations, and if you crave them, then boldly 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.
Untold story ...
Once a developer gets to a place where fate is decided. A time later, an image appears in front of him and asks:
- Who are you?
- I, the developer, call Ivan , - and to myself: In that stuck.
Voice again:
- Do you want to go there? . A look at the door, beyond which is paradise.
“Yeah ,” Ivan timidly.
- What will you tell me? - asks the Voice.
After a little thought, Ivan begins to say:
- There is in the java Enum-Almighty.
- How so, Almighty? - interrupts the voice indignantly. - This is just 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 , - the developer answers, But not only.
- Prove it!
- Enum like nails, scrap graves.
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;
}
/** Много статических методов здесь */
}
“So miracles, but ... He has no heir!”
- And this is how to look. And who should be considered the Heir? Scala? Kotlin?
- Give an example, without waiting until the developer completes his 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 guys, programmers - already smiling, says the Voice, - But it will be
small. Having scratched the 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?
|
Are you for Scala?
|
Are you for Kotlin?
|
- Joshua Bloch says * that this is Singleton's best implementation.
- Well, what about you?
- What about me? This, this - this is a singleton factory , for storing one single element, pounding pound ...
Highlander.valueOf("JAVA");
This is the point to access the array to store one single element, pound pound ...Highlander.values()[0];
This is the heir to the class ... , Ivan wanted to continue, but was pleasantly surprised:
- Come in ...
Some conclusions
In total, enum can be endowed with the following qualities and properties, depending on the point of view:
- Enumeration and data
- Utility class frame
- Singleton frame + antipater
- Factory frame
Experiment
I decided to understand how much it is possible to generate enumeration elements as much as possible. My own answer and reality were so diverged that I doubted my knowledge. Before you look below, try to give an answer yourself. Simplify, tell me at least the order? Here is the code that I used to generate the enumeration class (for quick reference):
Code Generation 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 the seven I managed to generate a total of 2746 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
[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 got this 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 file a bug at the Java Developer Connection (http://java.sun.com/webapps/bugreport) after checking the Bug Parade for duplicates. Include your program and the following diagnostic in your report. Thank you.
java.lang.IllegalArgumentException
Compiling 1 source file to / home / XXX / temp / BigEnum / bigenum / target / classes
An exception has occurred in the compiler (1.7.0_51). Please file a bug at the Java Developer Connection (http://java.sun.com/webapps/bugreport) after checking the Bug Parade for duplicates. Include your program and the following diagnostic in your report. 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
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 interested in how such an enumeration will be able to digest famous decompilers. Total subjective assessment of expectations:
A place | Decompiler | Result |
1 | fernflower.jar | OK |
2 | jad | Ok |
3 | procyon | Waited |
4 | cfr_0_115.jar | Not wait |
Thank you for attention.
Sources and inspirers
Effective Java, 2nd Edition, by Joshua Bloch *
Wikipedia
Correct Singleton in Java
Comment by apanasevich
Comment by Sirikid