Revert "Revert "Split Java libraries per apex""

This reverts commit f0f7ca8335cca669dd524b39d52997c28eb59e48.

Bug: 138182343
Test: apex_test added
Change-Id: I5c8a0935ac0f456137c8656815e220b0e7848a5d
diff --git a/java/hiddenapi_singleton.go b/java/hiddenapi_singleton.go
index c83dda1..8379f53 100644
--- a/java/hiddenapi_singleton.go
+++ b/java/hiddenapi_singleton.go
@@ -152,6 +152,14 @@
 		// Collect dex jar paths for modules that had hiddenapi encode called on them.
 		if h, ok := module.(hiddenAPIIntf); ok {
 			if jar := h.bootDexJar(); jar != nil {
+				// For a java lib included in an APEX, only take the one built for
+				// the platform variant, and skip the variants for APEXes.
+				// Otherwise, the hiddenapi tool will complain about duplicated classes
+				if a, ok := module.(android.ApexModule); ok {
+					if android.InAnyApex(module.Name()) && !a.IsForPlatform() {
+						return
+					}
+				}
 				bootDexJars = append(bootDexJars, jar)
 			}
 		}