Haxe Target-Specific Getting-Started Tutorials
←prev

Using Haxe in a Java Project

You have an existing Java project, and would like to use your own Haxe class(es) in it.

You can do this by first making a jar file from your Haxe code (compilation to Java and then creation of the jar file is done in one step), then use that jar file as you’d normally use any jar file.

Suppose you have:

my-haxe-lib/
    README.md
    src/
        my_stuff/
            Foo.hx

and in Foo.hx:

To make this work you’ll of course need to have Java installed, for example:

$ java -version
openjdk version "10.0.2" 2018-07-17
OpenJDK Runtime Environment (build 10.0.2+13-Debian-1)
OpenJDK 64-Bit Server VM (build 10.0.2+13-Debian-1, mixed mode)

To compile your Haxe file to Java you’ll have to install hxjava:

haxelib install hxjava

From your my-haxe-lib directory, compile your Haxe library like so:

haxe -cp src -java my_stuff -D no-root my_stuff.Foo

The -cp src tells haxe where to find the Haxe source file(s). The -java my_stuff tells haxe where to put the output. In the newly-created my-haxe-lib/my_stuff directory you’ll find the my_stuff.jar file; copy it into your Java project directory for use.

In that Java project directory, have a Main.java file containing:

Build and run in the usual way:

And get:

Hello, Java!
Foo.hx:5: Hi, Haxe!

For more info, see Phillipe’s answer on StackOverflow.