I had the need to instantiate some static nested Java classes, from within ColdFusion. I was doing some searching through IMAP. The Java code I was trying to emulate went something like this:

import javax.mail.*;
import javax.mail.internet.*;
InternetAddress address = new InternetAddress();
SearchTerm toTerm = new RecipientTerm(Message.RecipientType.TO, address);
SearchTerm ccTerm = new RecipientTerm(Message.RecipientType.CC, address);
SearchTerm bccTerm = new RecipientTerm(Message.RecipientType.BCC, address);
SearchTerm[] recipientTerms = {toTerm, ccTerm, bccTerm};
SearchTerm orTerm = new OrTerm(recipientTerms);

Notice that “Message” is never being instantiated. Thats because its a static class. “RecipientType” is a also static class, but its a nested class, created inside the Message class. The TO, CC, and BCC are static properties of that class.

It took me a while to figure this out in ColdFusion. I’m not a Java programmer so if I’m misstating something please feel free to correct me. We can get access to static classes in ColdFusion using createObject(), but the usual “.init()” is not necessary (and in fact will throw an error if used). And the key to instantiating an inner class is to use the $ sign. Here is what I came up with:

<cfset rec_type = createObject("java","javax.mail.Message$RecipientType")>
<cfset arrayTerms = ArrayNew(1)>
<cfset arrayTerms[1] = createObject("java","javax.mail.search.RecipientStringTerm").init(
    rec_type.TO,searchForThisEmail)>

<cfset arrayTerms[2] = createObject("java","javax.mail.search.RecipientStringTerm").init(
    rec_type.CC,searchForThisEmail)>

<cfset arrayTerms[3] = createObject("java","javax.mail.search.RecipientStringTerm").init(
    rec_type.BCC,searchForThisEmail)>

<cfset searchTerm = createObject("java","javax.mail.search.OrTerm").init(arrayTerms)>

I’ve needed to do this several times in working with the javax.mail libraries.

One Comment

  1. Jake says:

    Very nice work!