I have a library with common code which uses android.util.Log:
java_library(
name = "common",
srcs = glob(["*.java"]),
)
And I have an j2objc rule for iOS which works just fine:
j2objc_library(
name = "common_ios",
deps = ["//common"],
jre_deps = ["@bazel_j2objc//:android_util_lib"],
)
But when I use common in my Android project:
android_binary(
name = "app",
srcs = glob(["*.java"]),
manifest = "//android:manifest",
resource_files = ["//android:resources"],
deps = ["//common"],
)
But when I run bazel build //android:app, I get:
common/MyVeryOwnLogger.java:3: error: package android.util does not exist
import android.util.Log;
Which makes sense, as android.* libs should not be available in a java_library rule. Am I missing something? Is this not the recommended way to setup a project?
Thanks!
A
java_librarywon't be able to compile code that depends on Android because it won't have any of the Android dependencies thatandroid_libraryprovides.Have you tried running your iOS app with a dependency on
commonthat uses Android classes? I'm a little surprised that that works.In any case, I recommend moving things that are platform dependent out of
commonand into platform-specific rules.So, for example, say you have some kind of business logic
Modelclass incommonthat requires a logger, create some interface likeLoggerincommon, and haveModeltake an instance ofLogger. Then you can have anandroid_libraryrule that depends oncommonand provides an implementation ofLoggerfor Android that uses all the classes inandroid.util.*. Then yourandroid_binaryrule depends on bothcommonand theandroid_library. In your app code, you can then instantiate an instance of the Android-specific logger and pass that toModel.For the iOS half of things, you can similarly have an objective-c rule that provides iOS-specific logging (though I'm less familiar with how all that would work in objective-c or iOS).
You might also consider breaking up
commoninto separate rules, which will improve incrementality (e.g. putting logging into its own rule). This all depends on the structure of your code.