Serializing CFC's in ColdFusion 8
One of the handy new features in ColdFusion 8 is that CFC's are now serializable. There isn't a whole lot of information about this new feature in the docs, but I did some playing around and it does appear that they have used Java's serialization API. This means that you can use java's
java.io.ObjectOutputStream to serialize your CFC's...
Here's an example of how you might write serialize a CFC to a file:
<cfset myCFCInstance = CreateObject("component", "test")> <cfset myCFCInstance.setName("something")> <cfset fileOut = CreateObject("java", "java.io.FileOutputStream")> <cfset fileOut.init(ExpandPath("./serialized_cfc.txt"))> <cfset objOut = CreateObject("java", "java.io.ObjectOutputStream")> <cfset objOut.init(fileOut)> <cfset objOut.writeObject(myCFCInstance)> <cfset objOut.close()>
You will now have a file called
serialized_cfc.txt that you can open up. The file is actually a binary file, but you can read it with a text editor and see the values of your CFC instance variables inside this file.
Now suppose you want to read that file and reconstruct your CFC instance (deserialize it). We just use a
FileInputStream and a
<cfset fileIn = CreateObject("java", "java.io.FileInputStream")> <cfset fileIn.init(ExpandPath("./serialized_cfc.txt"))> <cfset objIn = CreateObject("java", "java.io.ObjectInputStream")> <cfset objIn.init(fileIn)> <cfset newCFCInstance = objIn.readObject()> <cfset objIn.close()> <cfoutput>#newCFCInstance.getName()#</cfoutput>
Now suppose you didn't want to write the CFC instance to a file, but rather store it as a value somewhere else... We can use a
ByteArrayOutputStream and then turn turn the Byte Array into a Base64 string.
<cfset byteOut = CreateObject("java", "java.io.ByteArrayOutputStream")> <cfset byteOut.init()> <cfset objOut = CreateObject("java", "java.io.ObjectOutputStream")> <cfset objOut.init(byteOut)> <cfset objOut.writeObject(myCFCInstance)gt; <cfset objOut.close()> <cfdump var="#ToBase64(byteOut.toByteArray())#">
Handy Stuff. Are there any functions or new features that I have missed that make this process any easier?
- Getting Size of Heap and Non Heap Memory in CFML - July 17, 2013
- Implicit Structure Notation ColdFusion - January 13, 2009
- 10 Most Useful Image Functions in ColdFusion 8 - April 5, 2008
- CFImage Effects Library for ColdFusion 8 - August 9, 2007
- CFThread - Don't Abuse It - August 7, 2007
There are probably more use cases for serialization when building Java GUI apps, than with building CF web apps, so thats why you hear java folks talking about it more.
- CFSummit 2016 Slides
- Securing Legacy CFML - dev.Objective() 2016 Slides
- My CFSummit 2015 Slide Decks
- Adding Chrome Custom Search for CFDocs
- Disable Flash Remoting on ColdFusion Servers
- HackMyCF Adds SSL/TLS Scanner
- IncompatibleClassChangeError after ColdFusion 11 Update 5
- Scope Injection in CFML