Skip to content

Commit af05e0a

Browse files
committed
fix init naming mismatch
Java's `init` methods are bridged as is and made swift compatible via the backticks. At runtime though, this is forgotten and the java methods are looked up _with_ the backticks. This approach of fixing adds a `@JavaMethod("init")` annotation, which fixes the issue. (Though I'm not sure if this shouldn't be fixed in the generated macro code. Open for suggestions!)
1 parent 0685f55 commit af05e0a

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed

Sources/SwiftJavaToolLib/JavaClassTranslator.swift

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -697,6 +697,11 @@ extension JavaClassTranslator {
697697
}
698698
// Do we need to record any generic information, in order to enable type-erasure for the upcalls?
699699
var parameters: [String] = []
700+
// If the method name is "init", we need to explicitly specify it in the annotation
701+
// because "init" is a Swift keyword and will be escaped in the function name via `init`
702+
if javaMethod.getName() == "init" {
703+
parameters.append("\"init\"")
704+
}
700705
if hasTypeEraseGenericResultType {
701706
parameters.append("typeErasedResult: \"\(resultType)\"")
702707
}

Tests/SwiftJavaToolLibTests/WrapJavaTests/BasicWrapJavaTests.swift

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,4 +88,36 @@ final class BasicWrapJavaTests: XCTestCase {
8888
)
8989
}
9090

91+
// Test that Java methods named "init" get @JavaMethod("init") annotation.
92+
// Since "init" is a Swift keyword and gets escaped with backticks in the function name,
93+
// we explicitly specify the Java method name in the annotation.
94+
// See KeyAgreement.init() methods as a real-world example.
95+
func test_wrapJava_initMethodAnnotation() async throws {
96+
let classpathURL = try await compileJava(
97+
"""
98+
package com.example;
99+
100+
class TestClass {
101+
public void init(String arg) throws Exception {}
102+
public void init() throws Exception {}
103+
}
104+
""")
105+
106+
try assertWrapJavaOutput(
107+
javaClassNames: [
108+
"com.example.TestClass"
109+
],
110+
classpath: [classpathURL],
111+
expectedChunks: [
112+
"""
113+
@JavaMethod("init")
114+
open func `init`(_ arg0: String) throws
115+
""",
116+
"""
117+
@JavaMethod("init")
118+
open func `init`() throws
119+
""",
120+
]
121+
)
122+
}
91123
}

0 commit comments

Comments
 (0)