20.20. Returning Typed Objects from Java

Problem

You want to return a typed object from a J2EE back end.

Solution

Use the third-party ASTranslator class to convert a JavaBean object to an ASObject, and return the ASObject.

Discussion

For details on obtaining ASTranslator, see Recipe 20.17.

Once you have ASTranslator included in your web application, you can use the toActionScript( ) method of an ASTranslator object to convert a JavaBean object into an ASObject that can be returned to Flash. Here is an example of a Java method that creates a JavaBean object, converts it into an ASObject, and returns the ASObject:

public flashgateway.io.ASObject getTypedObject(  ) {

  // Create a MyClass JavaBean object. See Recipe 20.14 for the MyClass code.
  MyClass myCls = new MyClass(  );
    
  // Set the properties of the object.
  myCls.setA("eh");
  myCls.setB("bee");

  // Create an ASTranslator object.
  com.carbonfive.flash.ASTranslator ast = new com.carbonfive.flash.ASTranslator(  );

  // Convert the MyClass object to an ASObject.
  flashgateway.io.ASObject aso = ast.toActionScript(myCls);

  // Return the ASObject.
  return aso;

}

Here is an example ActionScript snippet that handles the returned ASObject:

function MyClass(a, b) {
  this.a = a;
  this.b = b;
}
MyClass.prototype.a;
MyClass.prototype.b;

// Add a method that just writes all the properties to the Output window. This
// example illustrates that the ASObject is correctly converted into a MyClass object // when returned to Flash. MyClass.prototype.traceProperties = function ...

Get Actionscript Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.