This is something interesting I came across the other day, when I wanted to dynamically evaluate a static field on a Java class, and I thought it was a clever trick that was worth sharing.
First of all, what is a 'static field'? Well here is a really good description of a static variable, but the short version is that it something that is available without an instance of a class. This is functionality that can't be done in ColdFusion, but it is available in Java, and some other languages.
So if we look at a java.lang.Math we can see it has two static fields, one for pi, 'PI' and one for the value of e, 'E'.
In Java, we would be able to access these simply by going:
INT circumference = java.lang.Math.PI * diameter;
and if we wanted to do that in ColdFusion, we would have to do:
Math = createObject("java", "java.lang.Math");
circumference = Math.PI * diameter;
Now, what would we do, if we weren't sure if 'PI' existed on the Math class? In Java we'd have to do some reflection , but in ColdFusion, it is really, really easy:
hasPI = StructKeyExists(Math, "PI");
Yes – you can use Struct functions on the Java class to resolve public variables! Interesting, no?
So now, if we wanted to evaluate 'PI', we now have three options:
piOne = Math.PI; //as before
piTwo = Math["PI"]; //dynamically evaluate
piThree = StructFind(Math, "PI");
And all three will result in the same value.
This can be very handy when wanting to allow access to Java static fields on Class, but you don't want to be passing around a Java Object – now you can create a Facade to those Java objects, and ask for them dynamically.
I'm sure someone else can come up with a cleverer way to use this trick, but I found it useful.