Converting between JavaScript types and Java objects

Create a new AssemblyLine. Add no Connectors. Instead drop in a single Script Component. Now you have a simple test bed for your JavaScript snippets.

Now drop the script below into it and start playing around with converting between Java objects and JavaScript types:

// Create a Java Double, like we could get returned as
// an Attribute value, and that we access like this:
//
// var javaDoubleValue = work.getObject("someNamedAtt");
//
// Note that the above call gets the first value. You will want
// to look in the Java docs under the Entry and Attribute
// objects to see how to handle multiple Entries.
//
var javaDouble = new java.lang.Double(1.427);

task.logmsg("1. javaDouble - class: " + javaDouble.getClass());
task.logmsg("                value: " + javaDouble);

// Now I convert the double to a Java int using the convenient
// system.toInt() method. But first I turn the numeric value
// into a whole number by using the JavaScript Math.round()
// function.
//
var javaInt = system.toInt( Math.round(javaDouble) );

// I can make this the value of an Attribute like this:
//
//     work.setAttribute("integerAttribute", javaInt);
//
task.logmsg("2.    javaInt - class: " + javaInt.getClass());
task.logmsg("                value: " + javaInt);

// Now I use it in a JavaScript calculation. Just like with
// string expressions, if I mix JavaScript (the constant below
// "1.5") with Java objects, everything gets converted to JS -
// which only supports a few simple types: String, Number, Boolean,
// Date and Array (plus a couple more)
//
var jsNumber = javaDouble * 1.5;

try{
    // The .getClass() call below will fail because jsNumber is
    // a JavaScript type, not a Java object (which all have
    // the handy .getClass() method).
    //
    task.logmsg("3.   jsNumber - class: " + jsNumber.getClass());
} catch (excptn) {
    // If we end up here, we know jsNumber isn't a Java object.
    //
    task.logmsg("3.   jsNumber - class: No class, a JS Number.");
}

task.logmsg("                value: " + jsNumber);

//
// Check out this nice JavaScript reference:
//
//         http://www.w3schools.com/jsref/default.asp
//
// And this compressed one
//
//        http://javascript-reference.info/
//

-- EddieHartman - 16 Dec 2005
Topic revision: r1 - 16 Dec 2005, EddieHartman - This page was cached on 05 Aug 2023 - 18:54.

This site is powered by FoswikiCopyright © by the contributing authors. All material on this collaboration platform is the property of the contributing authors.
Ideas, requests, problems regarding TDI Users? Send feedback