Skip to content

Commit 091d49f

Browse files
committed
Improve and document the JavaVirtualMachine initializer
Add options for the class path (so clients don't need to re-learn how to spell it) and for telling the JVM whether to ignore unrecognized arguments.
1 parent c85371f commit 091d49f

File tree

1 file changed

+26
-4
lines changed

1 file changed

+26
-4
lines changed

Sources/JavaKitVM/JavaVirtualMachine.swift

Lines changed: 26 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -23,19 +23,41 @@ public final class JavaVirtualMachine: @unchecked Sendable {
2323
/// The JNI environment for the JVM.
2424
public let environment: JNIEnvironment
2525

26-
public init(vmOptions: [String] = []) throws {
26+
/// Initialize a new Java virtual machine instance.
27+
///
28+
/// - Parameters:
29+
/// - classPath: The directories, JAR files, and ZIP files in which the JVM
30+
/// should look to find classes. This maps to the VM option
31+
/// `-Djava.class.path=`.
32+
/// - vmOptions: Options that should be passed along to the JVM, which will
33+
/// be prefixed by the class-path argument described above.
34+
/// - ignoreUnrecognized: Whether the JVM should ignore any VM options it
35+
/// does not recognize.
36+
public init(
37+
classPath: [String] = [],
38+
vmOptions: [String] = [],
39+
ignoreUnrecognized: Bool = true
40+
) throws {
2741
var jvm: JavaVMPointer? = nil
2842
var environment: UnsafeMutableRawPointer? = nil
2943
var vmArgs = JavaVMInitArgs()
3044
vmArgs.version = JNI_VERSION_21
31-
vmArgs.ignoreUnrecognized = jboolean(JNI_TRUE)
45+
vmArgs.ignoreUnrecognized = jboolean(ignoreUnrecognized ? JNI_TRUE : JNI_FALSE)
46+
47+
// Construct the complete list of VM options.
48+
var allVMOptions: [String] = []
49+
if !classPath.isEmpty {
50+
let colonSeparatedClassPath = classPath.joined(separator: ":")
51+
allVMOptions.append("-Djava.class.path=\(colonSeparatedClassPath)")
52+
}
53+
allVMOptions.append(contentsOf: vmOptions)
3254

3355
// Convert the options
34-
let optionsBuffer = UnsafeMutableBufferPointer<JavaVMOption>.allocate(capacity: vmOptions.count)
56+
let optionsBuffer = UnsafeMutableBufferPointer<JavaVMOption>.allocate(capacity: allVMOptions.count)
3557
defer {
3658
optionsBuffer.deallocate()
3759
}
38-
for (index, vmOption) in vmOptions.enumerated() {
60+
for (index, vmOption) in allVMOptions.enumerated() {
3961
let optionString = vmOption.utf8CString.withUnsafeBufferPointer { buffer in
4062
let cString = UnsafeMutableBufferPointer<CChar>.allocate(capacity: buffer.count + 1)
4163
_ = cString.initialize(from: buffer)

0 commit comments

Comments
 (0)