It is fairly straightforward to create Java objects in Cold开发者_JS百科fusion:
variable = CreateObject("JAVA", "java.object").init(JavaCast("primitiveType", cfVar));
However, it isn't as straightforward to work with Java return types if, say, a Java method returns a list of Java objects:
newVariable = variable.returnJavaObjectCollection();
Is there a best practice for working with Java objects that are returned in an array or an ArrayCollection?
If I think I understand your question correctly (sorry, you aren't 100% clear) - you should be able to call methods on Java objects in ColdFusion, much as you would normally within Java.
For example, you can call methods on a java.lang.String object, when dealing with a String in ColdFusion.
So there is nothing wrong with:
<cfscript>
myString = JavaCast("string", "FooBar"); //definitely a String object.
</cfscript>
<cfoutput>
String length: #myString.length()#
Starts with 'Foo': #myString.startsWith("Foo")#
Upper case string: myString.toUpperCase()#
</cfoutput>
If you are dealing with an instance of java.util.List, you will find that 9/10 times, ColdFusion's native array functions will work just fine with - as ColdFusion Arrays are actually implementations of java.util.List as well.
So <cfloop array="#foo#" ...> should still work, ArrayAppend(), ArrayContains(), etc should all work as expected.
Failing that, you still have access to the underlying API for List: http://download.oracle.com/javase/6/docs/api/java/util/List.html
But the thing to remember, is that everything is from 0, rather than an index of 1.
So to get the first value in a Java List would be:
myItem = myList.get(0);
Rather than the CF way of:
myItem = myList[1];
Otherwise, that's really about it.
You should probably note that there is a small overhead on calling Java methods directly, as it is done on the fly using Reflection, so if you can use the native CF functions instead, that is usually better, but something you have no other recourse but to interact natively.
For more information you may want to try the ColdFusion Java Documentation
If your return a Vector<Object>
it will work with ColdFusion's array utilities, and a HashMap<String,Object>
will work with ColdFusion's Struct utilities. A few notes though:
null objects are not defined in ColdFusion, so if an element in the array is null, or a value in the map is null, or you just return null, their respective variables will be undefined.
Keep in mind that you can still call java methods on complex java objects in ColdFusion--including methods on sophisticated collections besides Vectors and Maps. For example:
<cfset iterator = myJavaObj.myJavaFuncReturnsCollection().iterator() />
<cfloop condition="iterator.hasNext()">
<cfset currObj = iterator.next() />
<cfset currObj.myFunction() />
</cfloop>
精彩评论