Revert "Revert "Split Java libraries per apex""

This reverts commit f0f7ca8335cca669dd524b39d52997c28eb59e48.

Bug: 138182343
Test: apex_test added
Change-Id: I5c8a0935ac0f456137c8656815e220b0e7848a5d
diff --git a/java/java.go b/java/java.go
index f3e10be..5f4a090 100644
--- a/java/java.go
+++ b/java/java.go
@@ -267,6 +267,7 @@
 type Module struct {
 	android.ModuleBase
 	android.DefaultableModuleBase
+	android.ApexModuleBase
 
 	properties       CompilerProperties
 	protoProperties  android.ProtoProperties
@@ -1550,7 +1551,8 @@
 	j.deviceProperties.UncompressDex = j.dexpreopter.uncompressedDex
 	j.compile(ctx, nil)
 
-	if (Bool(j.properties.Installable) || ctx.Host()) && !android.DirectlyInAnyApex(ctx, ctx.ModuleName()) {
+	exclusivelyForApex := android.InAnyApex(ctx.ModuleName()) && !j.IsForPlatform()
+	if (Bool(j.properties.Installable) || ctx.Host()) && !exclusivelyForApex {
 		j.installFile = ctx.InstallFile(android.PathForModuleInstall(ctx, "framework"),
 			ctx.ModuleName()+".jar", j.outputFile)
 	}
@@ -1581,6 +1583,7 @@
 		&module.Module.protoProperties)
 
 	InitJavaModule(module, android.HostAndDeviceSupported)
+	android.InitApexModule(module)
 	return module
 }
 
@@ -1603,6 +1606,7 @@
 	module.Module.properties.Installable = proptools.BoolPtr(true)
 
 	InitJavaModule(module, android.HostSupported)
+	android.InitApexModule(module)
 	return module
 }
 
@@ -1858,6 +1862,7 @@
 type Import struct {
 	android.ModuleBase
 	android.DefaultableModuleBase
+	android.ApexModuleBase
 	prebuilt android.Prebuilt
 
 	properties ImportProperties
@@ -2014,6 +2019,7 @@
 
 	android.InitPrebuiltModule(module, &module.properties.Jars)
 	InitJavaModule(module, android.HostAndDeviceSupported)
+	android.InitApexModule(module)
 	return module
 }
 
@@ -2029,6 +2035,7 @@
 
 	android.InitPrebuiltModule(module, &module.properties.Jars)
 	InitJavaModule(module, android.HostSupported)
+	android.InitApexModule(module)
 	return module
 }
 
@@ -2041,6 +2048,7 @@
 type DexImport struct {
 	android.ModuleBase
 	android.DefaultableModuleBase
+	android.ApexModuleBase
 	prebuilt android.Prebuilt
 
 	properties DexImportProperties
@@ -2132,6 +2140,7 @@
 
 	android.InitPrebuiltModule(module, &module.properties.Jars)
 	InitJavaModule(module, android.DeviceSupported)
+	android.InitApexModule(module)
 	return module
 }
 
@@ -2141,6 +2150,7 @@
 type Defaults struct {
 	android.ModuleBase
 	android.DefaultsModuleBase
+	android.ApexModuleBase
 }
 
 // java_defaults provides a set of properties that can be inherited by other java or android modules.
@@ -2199,7 +2209,7 @@
 	)
 
 	android.InitDefaultsModule(module)
-
+	android.InitApexModule(module)
 	return module
 }