Skip to content

Turbocharge Claude Code, Cursor, Codex, Gemini & every coding agent: faster, cheaper, with contextual understanding specific to your codebase.

fix(java): anonymous-class methods no longer take the enclosing type's owner (#161) (#176)

Frankie-Xu7039ab7a7fc7
diff --git a/src/graph/extract.ts b/src/graph/extract.ts
index 78fa1a09..d6f99ff2 100644
--- a/src/graph/extract.ts
+++ b/src/graph/extract.ts
@@ -466,6 +466,55 @@ function walk(node: Parser.SyntaxNode, ctx: WalkCtx, out: NodeV1[], edges: RawEd
}
}
+ // Java anonymous class (`new Type() { … }`): tree-sitter-java has no
+ // `anonymous_class` node (unlike PHP) — the body is an optional `class_body`
+ // on `object_creation_expression`. Mint `{anonymous}` (mirroring PHP #144 /
+ // `{closure}`) so nested methods take that owner instead of the enclosing
+ // type's, which otherwise pollutes `ownerMethod` and steals real call edges
+ // (#161). The constructor call edge above still fires for `new Type()`.
+ if (ctx.lang === "java" && node.type === "object_creation_expression") {
+ const body = node.namedChildren.find((c) => c.type === "class_body");
+ if (body) {
+ const idPart = "{anonymous}";
+ const base = `${ctx.rel}#${[...ctx.scope, idPart].join(".")}`;
+ const id = mintId(base, minted);
+ out.push({
+ id,
+ name: "{anonymous}",
+ kind: "class",
+ path: ctx.rel,
+ span: `L${node.startPosition.row + 1}-L${node.endPosition.row + 1}`,
+ signature: clean(ctx.source.slice(node.startIndex, body.startIndex)),
+ exported: false,
+ origin: "ast",
+ body_hash: contentHash(node.text),
+ body_text: searchBody(node.text),
+ summary_state: "pending",
+ summary: null,
+ crux: null,
+ });
+ edges.push({ source: ctx.parentId, relation: "contains", targetId: id, file: ctx.rel });
+ // Single supertype from `new Type()`: emit `implements` so an interface
+ // target resolves (adapters are the common case; a class target drops
+ // under resolve's implements kind filter — drop-not-guess).
+ const superName = javaConstructedTypeName(node.childForFieldName("type"));
+ if (superName) {
+ edges.push({ source: id, relation: "implements", name: superName, file: ctx.rel });
+ }
+ const anonCtx: WalkCtx = {
+ ...ctx,
+ scope: [...ctx.scope, idPart],
+ enclosingKind: "class",
+ parentId: id,
+ enclosingClass: "{anonymous}",
+ };
+ for (const child of node.namedChildren) {
+ walk(child, child.type === "class_body" ? anonCtx : ctx, out, edges, minted);
+ }
+ return;
+ }
+ }
+
for (const child of node.namedChildren) walk(child, ctx, out, edges, minted);
}
diff --git a/test/graph-java.test.ts b/test/graph-java.test.ts
index c5822b8c..87a3bd59 100644
--- a/test/graph-java.test.ts
+++ b/test/graph-java.test.ts
@@ -918,3 +918,97 @@ test("Java scopes: pom.xml, build.gradle, and build.gradle.kts are project marke
}
}
});
+
+/**
+ * Issue #161: a method inside an anonymous class body (`new Greeter() { … }`)
+ * used to take the enclosing type's `owner`, so `ownerMethod["App.greet"]` held
+ * both the real method and the anonymous override. `resolveTypedMember` then
+ * same-file first-wins tied to the anonymous impl, and `App.use → App.greet`
+ * vanished. Named nested classes already own their methods correctly — keep
+ * that as a control so this fix does not retarget lexical nesting.
+ *
+ * Shape mirrors PHP #144: mint `{anonymous}` and hang methods under it.
+ */
+const ANON_GREETER = `package com.acme;
+
+public interface Greeter {
+ String greet(String n);
+}
+`;
+
+const ANON_APP = `package com.acme;
+
+public final class App {
+
+ public Greeter make() {
+ return new Greeter() {
+ @Override public String greet(String n) { return "anon:" + n; }
+ };
+ }
+
+ public String use() {
+ App self = new App();
+ return self.greet("x");
+ }
+
+ public String greet(String n) { return "real:" + n; }
+
+ public static class Nested {
+ public String greet(String n) { return "nested:" + n; }
+ }
+}
+`;
+
+function anonOwnerFixture(): string {
+ const dir = mkdtempSync(join(tmpdir(), "graft-java-anon-"));
+ mkdirSync(join(dir, PKG), { recursive: true });
+ writeFileSync(join(dir, PKG, "Greeter.java"), ANON_GREETER);
+ writeFileSync(join(dir, PKG, "App.java"), ANON_APP);
+ return dir;
+}
+
+test("Java anonymous class: methods do not take the enclosing type's owner (#161)", async () => {
+ const dir = anonOwnerFixture();
+ try {
+ await buildGraph(dir);
+ const graph = readGraph(wiringPath(join(dir, "graft")))!;
+ const file = `${PKG}/App.java`;
+
+ const anon = nodeById(graph, `${file}#App.make.{anonymous}`);
+ assert.equal(anon?.kind, "class", "anonymous body mints an {anonymous} class node");
+
+ const anonGreet = nodeById(graph, `${file}#App.make.{anonymous}.greet`);
+ assert.equal(anonGreet?.kind, "method");
+ assert.equal(anonGreet?.owner, "{anonymous}", "anonymous greet is owned by {anonymous}");
+
+ const real = nodeById(graph, `${file}#App.greet`);
+ assert.equal(real?.owner, "App", "real App.greet keeps owner App");
+
+ const nested = nodeById(graph, `${file}#App.Nested.greet`);
+ assert.equal(nested?.owner, "Nested", "named nested class owner is unchanged");
+
+ assert.ok(
+ graph.edges.some(
+ (e) =>
+ e.relation === "implements" &&
+ e.source === `${file}#App.make.{anonymous}` &&
+ e.target === `${PKG}/Greeter.java#Greeter`,
+ ),
+ "anonymous class should implement Greeter",
+ );
+
+ const useCalls = graph.edges.filter(
+ (e) => e.relation === "calls" && e.source === `${file}#App.use`,
+ );
+ assert.ok(
+ useCalls.some((e) => e.target === `${file}#App.greet`),
+ `App.use should call the real App.greet; got: ${useCalls.map((e) => e.target).join(", ")}`,
+ );
+ assert.ok(
+ !useCalls.some((e) => e.target === `${file}#App.make.{anonymous}.greet`),
+ "App.use must not resolve to the anonymous greet",
+ );
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+});