Overview
swift4j is a library for calling Swift code from Java and Kotlin. You annotate Swift classes, structs, and enums with @jvm, run a code generator, and get proxy classes that let any JVM language use your Swift code as if it were a native Java library.
It works wherever a JVM runs: Android, macOS, Linux, and Windows.
How it works
Section titled “How it works”swift4j has two parts:
@jvm macro — applied to Swift types at compile time. The macro expands to JNI registration code that wires each exported method to a native C entry point inside the compiled Swift library.
generate-java-bridging plugin — an SPM command plugin that reads your Swift source files and generates Kotlin/Java proxy classes. Each proxy holds a pointer to the underlying Swift object and delegates method calls to the native stubs.
The workflow:
- Annotate Swift types with
@jvm - Run
swift package plugin generate-java-bridgingto generate Kotlin/Java proxy classes - Build your Swift package as a dynamic library
- In your JVM project, include the generated classes and load the library with
System.loadLibrary()
What can be exported
Section titled “What can be exported”- Classes, structs, and enums
- Instance and static methods
- Stored and computed properties
- Closures and callbacks
asyncmethods (mapped toCompletableFuture)@Observableclasses (with optional Android ViewModel generation)
See Using swift4j for details on each.