How do you use java files in Coldfusion

Does the file name need to be consistent with class name?

Do you mean the name of the .java file? Yes, but that is a java requirement. If your class is named "Hello", then your source file must be named "Hello.java" or it will not compile. When you compile the source code, the java compiler will generate a file named "Hello.class". Copy that file into the CF class path. The convention is to place individual .class files inside WEB-INF\classes and jar files inside WEB-INF\lib, as Adam mentioned. Note, you must restart the CF server for it to detect the new class(es)

After restarting, you will be able to create an instance of the class. However, be sure to use the correct class name in your createObject statement. It should be "Hello" - not "Test". Also, unlike most things in CF, the class name is cAsE sEnSiTive.

<cfscript>
    helloWorld = CreateObject("java","Hello");
    helloTest = helloWorld.testJava();
    WriteDump( helloTest );
</cfscript>


Update: That said, using individual class files is fine for testing purposes. However, you would normally package classes into a .jar file instead. With jar files, the file name is irrelevant. Only the internal path to the class matters. If your class resides in a package, you must include the package name as well. For example, if your Hello class resides in a package named com.utilities, the full path would be:

 helloTest  = createObject("java", "com.utilities.Hello");

In terms of the class path, usage is the same. Just place the jar file in the CF class path ie WEB-INF\lib and restart. As Raymond mentioned in the comments, for CF10+ see Specifying custom Java library path in the Application.cfc without dynamic loading.


You need to put the files on the ColdFusion JVM's classpath, not in its JRE dir.

As a rule, if you have a jar file, put it in the instances's WEB-INF/lib dir, if it's just a class, put it in the WEB-INF/classes dir, eg: for me the latter would be C:\apps\adobe\ColdFusion\11\full\cfusion\wwwroot\WEB-INF\classes, where C:\apps\adobe\ColdFusion\11\full\ is where I installed CF, and cfusion is the name of the instance.