Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to create Java enums based on input file?

Tags:

java

enums

I'm using Java 6.

Suppose I have a file availableFruits.txt

APPLE
ORANGE
BANANA

Suppose I want an enum FruitType that contains values listed in availableFruits.txt, will I be able to do this?

like image 515
Russell Avatar asked Dec 10 '10 13:12

Russell


People also ask

Should Java enums be in their own file?

You don't have to declare an enum in a separate file.

Can we assign values to enum in Java?

By default enums have their own string values, we can also assign some custom values to enums.

Are enums passed by reference Java?

In Java you cannot pass any parameters by reference. The only workaround I can think of would be to create a wrapper class, and wrap an enum. Now, reference will contain a different value for your enum; essentially mimicking pass-by-reference.


3 Answers

You can't populate an enum type at execution time, no - at least, not without something like BCEL, or by calling the Java compiler.

You can write code to create a Java source file, of course, and build that when you build your app, if you don't need it to be changed afterwards.

Otherwise, I'd just create a wrapper class which is able to take a set of known values and reuse them. Exactly what you need to do will depend on how you wanted to use the enum, of course.

like image 124
Jon Skeet Avatar answered Oct 01 '22 10:10

Jon Skeet


Well the point of an Enum is to use it at compile time. If you don't know at compile time what values your Enum has then it's not an Enum it's a collection.

If you do know and you just want to create a class file base on the values in the text file then yes it's possible by reading the txt then generating the source code.

like image 40
Liviu T. Avatar answered Oct 01 '22 11:10

Liviu T.


I expect it's possible, by writing your own ClassLoader subclass, creating the bytecode for the enum in a byte array, and using defineClass. Hard, maybe, but possible. I expect once you know the byte sequence for an enum, it's not that hard to custom-generate it from the info in the JVM spec.

Now, whether it's a good idea...well, I suspect only in a very small number of edge cases. (I can't think of one; I mean, having created it, you'd have to generate code to use it, right?) Otherwise, you're probably better off with a Map or similar.

like image 39
T.J. Crowder Avatar answered Oct 01 '22 10:10

T.J. Crowder