ColdFusion 8 Respects Java Generics
Andrew Powell
A lot of people do not realize that by moving from ColdFusion 7x to ColdFusion 8x, you are actually switching JVM versions as well. This is important because there a few significant changes to the Java language between Java 1.4 and Java 1.6 (a.k.a. Java 6). Java 1.5 (a.k.a. Java 5) introduced two things that are especially significant in that world, annotations (JSR-175,JSR-269) and Generics (JSR-14). Let's focus on generics for now, annotations will come later.
So, what are generics?
Sun says: "It adds compile-time type safety to the Collections Framework and eliminates the drudgery of casting." OK, that's all well and good, but what does it mean? It means that when the compiler runs, variables are checked for type correctness, not at run time. Let's take a look at some code to explain.
List myList = new ArrayList();
myList.add("myVar");
String a = (String) myList.get(0);
Integer b = (Integer) myList.get(0);
The above code will compile, but it will throw an exception at runtime (java.lang.ClassCastException). There are three issues with this code as well:
- This ArrayList is simply an ArrayList of Objects, but we want it to be an ArrayList of only type String.
- Line 4 will throw an error at runtime, but will compile just fine.
- It's just a pain to cast variables all over the place.
List<String> myList = new ArrayList<String>();
myList.add("test");
String a = myList.get(0);
Integer b = myList.get(0);
At compile-time, line 4 will throw an exception. You can only add objects of type "String" to the variable "myList".
So where does ColdFusion fit into all this? Well, if you have an ArrayList<String> ColdFusion will see it as an Array. It will work as an Array does in ColdFusion, but you will still have access to all the ArrayList functionality in ColdFusion. However, if you try to add an Object of any type other than String, ColdFusion will throw an exception of type java.lang.ClassCastException. This means that you have to be very careful when working with generics, or have good documentation when it comes to your Java model. If you don't know that you are working with a generic collection, you can bang your head against a wall for a while trying to figure out where the error is coming from in the code.
Posted in Java | ColdFusion | General | Universal Mind |
3 comments
May 15, 2008 at 2:16 PM BTW, the description of what generics are is a paraphrase of Wikipedia's enty on Java Generics
May 15, 2008 at 8:18 PM I'm accustomed to generics through C# ... but to better understand your points:
you're saying this only applies to manipulating generic Java objects in ColdFusion, yes?
May 17, 2008 at 10:46 AM @Barry yes, I'm specifically discussing manipulating Java generics in CF. I would think it would probably respect .NET generics as well via it's .NET integration.