I'm trying to declare an enum type based on data that I'm retrieving from a database. I have a method that returns a string array of all the rows in the table that I want to make into an enumerated type. Is there any way to construct an enum with an array?
This is what I tried, but from the way it looked in eclipse, it seemed like this just created a method by that name:
public enum ConditionCodes{
Condition.getDescriptions();
}
Thank you in advance!
You can't.
The values of an enum must be known at compile time. If you have anything else, then it's not an enum.
You could come rather close via an implementation that's similar to the old typesafe enums that were used before the Java language introduced support for this technique via the enum keyword. You could use those techniques but simply replace the static final fields with values read from the DB.
For your enum to be useful it has to be nailed down at compile time. Generating the enum from the database query would imply you expect to see new enum values at runtime. Even if you created a code generator to create your enum class on the fly using the database query, you wouldn't be able to reference those enum values in your code, which is the point of having them.
It's difficult to see how any compiler could support this.
The whole point of an enum is supposed to be that you get compile-time checking of the validity of your values. If, say, you declare an enum "enum MyStatusCode {FOO, BAR, PLUGH}", then in your code if you write "MyStatusCode.FOO" everything is good, but if you write "MyStatusCode.ZORK" you get a compile-time error. This protects you from mis-spelling values or getting confused about the values for one enum versus another. (I just had a problem recently where a programmer accidentally assigned a delivery method to a transaction type, thus magically changing a sale into an inventory adjustment when he meant to change a home delivery into a customer pick-up.)
But if your values are defined dynamically at run-time, how could the compiler do this? If you wrote MyStatusCode.ZORK in the above example, there is no way the compiler could know if this value will or will not be in the database at runtime. Even if you imagined a compiler smart enough to figure out how the enum was being populated and checking the database to see if that value is present in the appropriate table NOW, it would have no way of knowing if it will be there when you actually run.
In short, what you want is something very different from an enum.
If you want to get really crazy, I think annotation processing can do this. Annotation processing lets you hook the compiler and have it magically modify things when your #annotation is present.
Naturally, the values in the enum will be whatever values were available at compile time.
No, that's not possible because the enum type must be defined at compile time and what you're looking for is to dynamically create it.
Perhaps you'll be better if use a class instead.
I think here you are going to need a List or Set along with some utility methods for searching and comparison.
So here's your List
List<String> conditionCodes = new ArrayList<String>();
//Somehow get Rows or POJO Beans from database with your favorite framework
Collection<Row> dbRows = getConditionCodes();
for(Row curRow : dbRows)
conditionCodes.add(curRow.getName());
And to search
public boolean conditionExists(String name) {
return conditonCodes.contains(name);
}
public String getCondition(String name) {
return conditionCodes.get(name);
}
(of course you would probably want to use List's own methods instead of making your own)
More than you can't, you don't want to. Every enum, even Java's fairly cool enums, is code oriented.
It's exactly the same as a collection, but with an enum you tend to write duplicate code whenever you encounter it--with a collection you are more likely to write a loop.
I suggest you create a class with a private constructor and have it create the instances of itself, then provide a getInstance(String) to retrieve an instance. This is like the old typesafe enum pattern.
In the long run, however, it's better if you can manage to get enough intelligence into that class where you aren't ever differentiating on a specific instance--going from the "Enum" way of doing it:
if(myEnum.stringValue.equals("EnumTarget"))
executeCode();
To the OO way of doing it:
myEnumLikeObject.executeCode();
Moving the code you wish into the "enum"--preferably delegating directly to a contained object that is instantiated and set into the "enum" at creation time.
Related
I have lot of static/constant data which I want to store, this data is also related with each other. I can use lot enums referencing each other forming a tree or a graph. Or simply use tables or database enums and store values in them and create corresponding classes and respective relationships. The data I have is constant and is certainly not going to change. I might have to also consider internationalization in near future. I will be using this constant data as filter to various other data.
I am tempted to use enums as it gives me immutability by default, but seeing the complexity of relationship between data, like I might have to sacrifice with inheritance, I am also little apprehensive of enums. And populating these enum classes from database and internationalization might be little more tricky. And at later stage hoping that it will scale and embrace the complexity with ease are the areas of concern as I would not like to revert from the mid way.!
---Update---
I have not seen examples of enums related(associations) with each other, containing fields of complex types referencing other enums. Can in this type of cases enums replace classes when data is constant.
Is there any objective way to look at this problem.
To understand better, I have similar classification like below.
Animal Kingdom having tree hierarchy
While this Question is likely too broad for Stack Overflow, a few thoughts.
Enums
You may not fully understand the enum facility in Java. See the Oracle Tutorial, and see the Enum class doc.
An enum is a class, a regular Java class, a subclass of Enum. The only thing special is that syntactic sugar that automatically instantiates the static instances you define and name. Otherwise, they are normal classe:
Your enums can carry member variables.
Your enums can have constructors, and you can pass arguments to those constructors.
Your enums can offer other methods, and you can pass arguments to those methods.
You can even pass instances of one enum as arguments to methods of another enum’s instances – just as you might pass instances of an enum to instances of other non-enum classes. Each enum instance is just an object, plain and simple, saved as a static reference on the enum-defining class.
Example:
public enum Food { HERBIVORE, OMNIVORE, CARNIVORE ; } // Syntactic sugar for automatically instantiating these named static instances of this class type.
…and…
public enum Animal {
RABBIT( Food.HERBIVORE ) ,
DOG( Food.OMNIVORE ) ,
CAT( Food.CARNIVORE ) ;
// Member variables.
public Food eats ;
// Constructor
Animal( Food foodType ) {
this.eats = foodType ; // Assign an instance of another enum to this instance of this enum.
}
}
Limitations of enums
While more powerful and useful than in other languages, there are limitations.
Compile-time
Firstly, enums are defined at compile-time. If your values change at runtime, perhaps you want to add or delete items, then enums are not appropriate.
Permanently in memory
Also, enums are static. This means when first used, all the objects of that enum class are instantiated immediately and held in memory throughout the execution of your app. So they are never retired from memory until program ends. So having an enormous number of them might be a burden on memory.
Understand that your can collect enum instances. See the EnumSet and EnumMap classes for fast-to-execute and low-memory usage collections of enum instances. Search Stack Overflow for much coverage on this topic. And be aware that every enum carries a values() method that returns an array of its values, yet this method is mysteriously not listed in the JavaDoc.
As for your mention inheritance, your enums by definition are subclasses of Enum class. So they cannot inherit from any other class you may have in mind, as Java does not support multiple-inheritance. Your enums can implement one or more interfaces. In later version of Java, an inheritance can carry implementation code by way of new default methods, so you can pass along some code that way.
Internationalization
Internationalization and localization seems to be an orthogonal issue. You can add a method on your enum to generate localized String representation of their value. As an example, see DayOfWeek::getDisplayName and Month::getDisplayName enum methods.
Database
If you want to dynamically define your values at runtime, or you have zillions of them, then a database is the way to go. A serious database such as Postgres is designed to manage memory, handle concurrency, and execute efficiently.
You can even combine enums with the database. For example, localization. You might have enum values defined at compile-time, but their getDisplayName method does a lookup into a database to find the French or Arabic translation. That translation value in the database can be updated during runtime by running SQL INSERT or UPDATE commands via JDBC.
Recursive hierarchical relationships
If you are trying to represent relationships of a hierarchy of arbitrary depth, that is a whole other topic I'll not address here other than to say that is often implemented with recursion. Search Stack Overflow and other sources to learn more.
As a rule of thumb, I only involve a database when the values are likely to change faster than code release cycles, and when it's possible or likely that someone who is not me is going to change them. Making the code depend on a running (and available) database means that when some DBA takes the database down for maintenance then your application can't be started.
There exists an enum class that will cause problems downstream if it is changed without also making changes to the downstream project. Unfortunately, this is not easily identified by just searching for usages of the enum. We have had big warning comments in the code saying "Don't change this without also changing (downstream project)", but apparently that wasn't enough: Murphy's Law held firm. I need some other way of preventing other developers (or future me) from breaking things.
My current approach is to create a Unit test that will throw an error whenever the enum is changed. Changing the enum will therefore cause the build to fail which should get the attention of the developer. Included in the failure message will be instructions on how to safely update the enum. Unfortunately I can't see any way of writing this unit test short of copying the entire enum into the test class and then comparing every value from the test enum to the actual enum.
Is there a way that I can avoid duplicating the enum in the test class here? Is there a best practice that you recognize I should be following based on my description?
If all you want to verify is the enum member names and maybe their order, then you can create a static method on the enum type that computes a digested form of that information. Your unit test can then invoke a single method to test whether the enum matches expected form.
For example,
enum Test {
T1;
static int computeSignature() {
StringBuilder sb = new StringBuilder();
for (Test t : values) {
sb.append(t.name()).append(';');
}
return sb.toString().hashCode();
}
}
// ...
private final static int EXPECTED_ENUM_SIG = /* some number */;
#Test
public void testEnumSignature() {
assertEquals("enum Test has been unexpectedly changed", EXPECTED_ENUM_SIG,
Test.computeSignature());
}
If you decide you don't care about the enum order, then sort the names as part of the signature computation.
Once an enum class is published it becomes part of the Public API and for the most part, should not be changed. Enum constant names should definitely should not be changed and you probably shouldn't add any new constants either.
This really isn't that much different than changing method signatures on interfaces and should be treated the same way.
Any change is an API breaking change and will affect any downstream programs that link to your enum.
If you really must change your enum then your library should bump up the major version number and include detailed release notes explaining the change and exactly what must be done to make old code compatible.
Unfortunately, the workarounds for enums are not pretty.
Since you can't extend enums if you want to add new enums you can't just extend the old enum class and add a few more constants.
I would recommend extracting an interface for the methods in the enum and have your enum class implement the new interface and try to get your downstream software to only use the interface. Then future versions of your code can add new constants with less problems. But the initial transition to an interface will be painful but hopefully only happen once.
This is covered in some detail in Effective Java 2nd Edition Item 34: "Emulate extensible enums with interfaces"
Suppose I have an Employee class. How can I implement an ArrayList only containing Employee elements without using generics? That is, without Arraylist<Employee>, how can I restrict the ArrayList to add only Employee objects?
Extend ArrayList and customize add() and addAll() method to check the object being added is instanceof Employee
You could use a wrapper class that holds a private ArrayList field, say called employeeList, has a
public void add(Employee employee) {
employeeList.add(employee);
}
as well as any other necessary methods that would allow outside classes to interact with the ArrayList in a controlled fashion.
I find it much better to use composition for this than inheritance. That way if you wanted to change from an ArrayList to something else, say a LinkedList, or even something completely different, you would have an easier time.
You could use Collections.checkedList() - but why would you want to not use generics?
Subclass the ArrayList class and name it something like EmployeeArrayList.
If you're wanting to avoid generics for their own sake, e.g. for compatibility with very old versions of Java, then extending or wrapping ArrayList won't help - you probably want to find or make another array implementation that has the same functionality.
Basically, ArrayList is just a wrapper for a primitive array that copies and pastes its data into a larger array when necessary, so this isn't especially difficult to write from scratch.
What exactly do you want when you "restrict"? There are two possible places where one could place a restriction: at compile-time or runtime.
Generics is a purely compile-time thing. It helps you write correct code but you can still bypass it and put the wrong type in the array and it won't complain at runtime.
On the other hand, something like Collections.checkedList()is a runtime restrictions. It throws an error at runtime when an object of the wrong type comes. But it does not help you at compile-time if you do not have generics.
So the two things are orthogonal, and neither is a replacement for the other. What exactly do you want?
I have an interface, GenericExpression, that gets extended to create expressions (ie AndExpression, OrExpression etc.).
Each GenericExpression implementation has a string that represents it (ie "&", "+", etc.) (stored as a static variable "stringRep")
Is there any way to take a user input String and check if it represents a GenericExpression?
If not (seems likely this is the case), is there any way to achieve a similar effect with a refactored design?
Thanks!
EDIT: Offered a little bit more detail above.
Also, the end goal is to be able to arbitrarily implement GenericExpression and still check if a string represents an instance of one of its subclasses. As such, I can't just store a map of implementation - string representation pairs, because it would make make it so GenericExpression is no longer easily extendible.
Also, this is homework
Well I think you will need to define somewhere what expressions are supported by your program. I think the best way is to use a map, where you map your interface to strings. That way you can easily look up an expression with its representing string. Where you will define this map is dependant on your design. One possibility is a static method in a helper class that resolves expressions to a string like:
Expressions.get("&").invoke(true, false);
Where get is a static method on Expressions that looks up the desired expression in a static map. You will have to initialize this map in a static initializer, or let the expression instances add themselves on creation.
EDIT:
(I wanted to comment this on an answer but it seems to be deleted)
Personally I don't like the idea of classes registering themselves. It gives me the feeling of not being in control of my code. I would prefer to instantiate the classes in the Expressions class itself. The code for registering a class must be written for every new subclass anyway. I prefer to centralize this code in a single class so if I want to change logic or refactor, I only have to touch one class.
Looking at some code cleanup and I was wondering the best way to deal with this:
Have a class with some private variables like:
myBool1, myBool2, myBool3
myInt1, myInt2, myInt3
myString1, myString2, myString3
What's the best way to do a getter function that is generic to the return value? So if I do a call to the getter with something like:
myNewBool=<blah>.get("myBool1")
myNewString=<blah>.get("myString2")
myNewInt=<blah>.get("myInt3")
Anyone have any suggestions?
You can't really have a generic getter if you don't know what you want to get, for example :
boolean myNewBool= get("myString1");
If get returns something, but you don't really know if this something is compatible with a boolean, and terrible things could happen.
You could try this:
public <T> get(String element){
return (T) elementToGet;
}
But you would have to specify the return type when you call the get method.
String element = myObject.<String>get("element");
Here are the bad sides :
You can't work directly with primitives
You can have a lot of ClassCastException
If you misspell an attribute name you won't see it until you run it
You don't expose a nice public API, people would have to know evert possible attribute to use it, and as said above, a misspelled attribute (or an inexistant one) wouldn't be seen until runtime.
You have to know the return time and type it each time you use your method
You would have to type a really long (and smelly) code in your get method either to use each possible attribute (if you still want have some private and not accessible) or worse, use reflection to find the right attribute.
So definitively not a good idea.
What you can do instead is using the good old getters//setters and if there is a lot of them, generate them with your IDE.
Another way would be to use the project lombok.
Resources :
Project Lombok
On the same topic :
Create automatically only getters in Eclipse
Eclipse Generate All getters setters in package
Java Getters and Setters
First you should ask what would be the pros and cons of such a solution.
Pros:
One method instead of many
Cons:
Non-intuitive to the users of your class (classical getters are more common)
You cannot have an overload that only differs by a return type, therefore you will have to have methods like getBool, getInt etc.
It's slower - you have to pass the string, check for validity, do a lookup in a map...
The only advantage of your proposed solution would be not repeating the get()/set() code. However, as these methods are usually generated by your IDE and contain only a single-line command, I wouldn't see that as a big problem.
To answer your actual question - you can create a HashMap with name-attribute mapping. Alternatively, you may use Java reflection to access the attributes. The second solution is more general but also harder to write.
This is really a terrible idea. I'm not sure why creating a getter/setter for each private variable is a problem, but passing around strings that map to a variable's symbolic name would be hard to maintain and confusing. You don't need this to be generic; each variable represents a different quantity and they should be accessed as such.
It wouldn't be clean up but mess up. I'd either created 3 getter methods for the fields or redesign it completely. But calling a function, with a name of a field to return, as an argument can bring nothing good.
When you code, you must be refactoring your code for all the time you are coding. But not like this. Solution is delegating logic to another class, wrapping code into more utilizable methods or changing and simplifying domain objects...