Is it possible to create an empty Java enum type with methods?
I can create an empty Java enum type, but when i want to add some methods : i get a "syntax error" (into Eclipse). I found no official documentation about this,开发者_运维问答 so my question is : is it just impossible (so where is it clearly mentioned?) or is it just the compiler which is wrong ?
Yes it's possible. You just need to add a ;
to terminate the (empty) list of enum constants:
enum TestEnum {
; // doesn't compile without this.
public void hello() {
System.out.println("Hello World");
}
}
JLS Syntax Definition for enum
s
(Note that without any instances, you'll only be able to call the static
methods of the Enum.)
Related:
- Zero instance enum vs private constructors for preventing instantiation
Of course you can! "Ia! Ia! Cthulhu Fthagn! Ph'nglui mglw'nfah Cthulhu R'lyeh wgah'nagl fhtagn!!"
Original idea: "http://www.theserverside.com/news/thread.tss?thread_id=50190"
Destroy reality at your own risk.
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
enum ThingsThatShouldNotBe {
;
public void HelloWorld() {
System.out.println(this.name() + " Says Hello!");
}
public static void main(String[] args) throws Exception {
Constructor<?> con = ThingsThatShouldNotBe.class.getDeclaredConstructors()[0];
Method[] methods = con.getClass().getDeclaredMethods();
for (Method m : methods) {
if (m.getName().equals("acquireConstructorAccessor")) {
m.setAccessible(true);
m.invoke(con, new Object[0]);
}
}
Field[] fields = con.getClass().getDeclaredFields();
Object ca = null;
for (Field f : fields) {
if (f.getName().equals("constructorAccessor")) {
f.setAccessible(true);
ca = f.get(con);
}
}
Method m = ca.getClass().getMethod("newInstance",
new Class[] { Object[].class });
m.setAccessible(true);
ThingsThatShouldNotBe v = (ThingsThatShouldNotBe) m.invoke(ca, new Object[] { new Object[] { "Cthulhu",
Integer.MAX_VALUE } });
System.out.println(v.getClass() + ":" + v.name() + ":" + v.ordinal());
System.out.println("Say hello Cthulhu!");
v.HelloWorld();
}
}
Mwu HA HA HA HA HA HA.
If you really need an Enum and you want it to have instance methods, and you have resolved to summon the elder gods of reflection to force this abomination upon the world, then it is useful.
This will definitely confuse the heck out of other developers later.
Yes, it is:
You need to add a semicolon (;
) to terminate the empty list of enums.
This compiles:
public enum MyEnum {
;
public void method() {
}
}
Although I can't think what it would be useful for.
Absoulely,
/**
* @author The Elite Gentleman
* @since 06 September 2011
*
*/
public enum ExampleEnum {
WHAT_ENUM
;
public void doOperation() {
}
}
Later:
ExampleEnum exEnum = ExampleEnum.WHAT_ENUM;
exEnum.doOperation();
精彩评论