Newsletter sign-up
View all newsletters

Enterprise Java Newsletter
Stay up to date on the latest tutorials and Java community news posted on JavaWorld

JavaWorld Daily Brew

Invoking JavaFX functions that don't exist

 

What happens when you try to execute the following Java code fragment?

String s = null;
System.out.println (s.length ());

It's not hard to figure out that a NullPointerException object is thrown. You cannot invoke a method via the null reference.

However, you can get away with something similar in JavaFX Script, which the following code fragment demonstrates:

var x: function (): Void;
println (x); // Output: null
x ();
x = null;
x ();
x = function (): Void { println ("x() invoked") }
x () // Output: x() invoked

The code fragment initially creates variable x of type function (): Void. Furthermore, this variable is initialized to null, which the subsequent println (x); expression proves.

Notice the first x (); invocation. You might expect that the JavaFX runtime would throw a NullPointerException, but this doesn't happen. In fact, the invocation is ignored.

To make this more explicit, the code fragment assigns null to x and once more executes x ();. Same result.

Finally, the code fragment assigns an anonymous function to x and executes x (), which results in the function being invoked and outputting x() invoked.

This "ignore a function invocation when the function variable contains null" behavior is present in JavaFX 1.0 and 1.1, and appears to be a useful feature for making code more robust. However, it can also mask bugs when a function must be executed but never is because its function variable contains null.

Do you think that a NullPointerException should be thrown in this situation, or is the ignore behavior okay with you?