Ensure APEX's Java deps use stable SDKs.

Test: m
Bug: 153333044
Change-Id: Ib1acf3073e96fe23c92d292ec0b1a91e2cd408db
Merged-In: Ib1acf3073e96fe23c92d292ec0b1a91e2cd408db
Exempt-From-Owner-Approval: cp from aosp
(cherry picked from commit 8cf899afcc69643f63350bc9f9f92677bb8feabd)
diff --git a/apex/apex.go b/apex/apex.go
index 6a0c4c1..7191365 100644
--- a/apex/apex.go
+++ b/apex/apex.go
@@ -1871,6 +1871,8 @@
 		if String(a.properties.Min_sdk_version) == "" {
 			ctx.PropertyErrorf("updatable", "updatable APEXes should set min_sdk_version as well")
 		}
+
+		a.checkJavaStableSdkVersion(ctx)
 	}
 }
 
@@ -1940,7 +1942,6 @@
 
 	a.checkApexAvailability(ctx)
 	a.checkUpdatable(ctx)
-
 	a.collectDepsInfo(ctx)
 
 	handleSpecialLibs := !android.Bool(a.properties.Ignore_system_library_special_case)
@@ -2247,6 +2248,23 @@
 	a.buildApexDependencyInfo(ctx)
 }
 
+// Enforce that Java deps of the apex are using stable SDKs to compile
+func (a *apexBundle) checkJavaStableSdkVersion(ctx android.ModuleContext) {
+	// Visit direct deps only. As long as we guarantee top-level deps are using
+	// stable SDKs, java's checkLinkType guarantees correct usage for transitive deps
+	ctx.VisitDirectDepsBlueprint(func(module blueprint.Module) {
+		tag := ctx.OtherModuleDependencyTag(module)
+		switch tag {
+		case javaLibTag, androidAppTag:
+			if m, ok := module.(interface{ CheckStableSdkVersion() error }); ok {
+				if err := m.CheckStableSdkVersion(); err != nil {
+					ctx.ModuleErrorf("cannot depend on \"%v\": %v", ctx.OtherModuleName(module), err)
+				}
+			}
+		}
+	})
+}
+
 func whitelistedApexAvailable(apex, moduleName string) bool {
 	key := apex
 	moduleName = normalizeModuleName(moduleName)