Read Bazel config from Java code

Skip to first unread message

Rafal Orlowski

Jun 11, 2024, 5:05:27 AMJun 11
to bazel-discuss

I have java project that is built with Bazel. Now I want to add compilation flag which I can read from java code and do some conditional work upon it. How can I achieve it?

Best regards
Rafal Orlowski

Allan Clark

Jun 12, 2024, 12:04:16 AMJun 12
to bazel-discuss
This is a really open-ended question, but many here like a challenge.

To be a bit more precise, can you create a github project/repo that demonstrates what you’d like to do, where the config would be held, what parts would be changed by reading it?

Chances are, it’s easier to control both your Java code and the conditional work, and you may find yourself defining all possible targets, but conditionally selecting one as a dependency to get one of a few possible conditionals compiled.

Please share a repo showing the problem, and let us suggest a fix?  Mark it up with comments or however to describe what’s not quite what you need.


Prasanna Swaminathan

Jun 14, 2024, 7:38:14 PMJun 14
to bazel-discuss
This sounds analogous to Gradle's BuildConfig for Android. There is some prior art for that here, though you'll have to adapt it for your needs. A trivial example like

    name = "build_config_base",
    outs = [""],
    cmd = """
cat << EOF > $@

public class BuildConfig {
    public static final String TARGET = "$(TARGET)";

    name = "build_config",
    srcs = [":build_config_base"],

    name = "app",
    srcs = [""],
    deps = [":build_config"],
    main_class = "",

Would allow you to set it/use it with, e.g. bazel build --define=TARGET=myapp. If you wanted to use it more broadly, you could wrap the genrule + java library in a macro.
Reply all
Reply to author
0 new messages