Java Rules

Report an issue View source Nightly · 7.3 · 7.2 · 7.1 · 7.0 · 6.5

Rules

java_binary

View rule source
java_binary(name, deps, srcs, data, resources, args, classpath_resources, compatible_with, create_executable, deploy_env, deploy_manifest_lines, deprecation, distribs, env, exec_compatible_with, exec_properties, features, javacopts, jvm_flags, launcher, licenses, main_class, output_licenses, plugins, resource_jars, resource_strip_prefix, restricted_to, runtime_deps, stamp, tags, target_compatible_with, testonly, toolchains, use_launcher, use_testrunner, visibility)

Builds a Java archive ("jar file"), plus a wrapper shell script with the same name as the rule. The wrapper shell script uses a classpath that includes, among other things, a jar file for each library on which the binary depends. When running the wrapper shell script, any nonempty JAVABIN environment variable will take precedence over the version specified via Bazel's --java_runtime_version flag.

The wrapper script accepts several unique flags. Refer to //src/main/java/com/google/devtools/build/lib/bazel/rules/java/java_stub_template.txt for a list of configurable flags and environment variables accepted by the wrapper.

Implicit output targets

  • name.jar: A Java archive, containing the class files and other resources corresponding to the binary's direct dependencies.
  • name-src.jar: An archive containing the sources ("source jar").
  • name_deploy.jar: A Java archive suitable for deployment (only built if explicitly requested).

    Building the <name>_deploy.jar target for your rule creates a self-contained jar file with a manifest that allows it to be run with the java -jar command or with the wrapper script's --singlejar option. Using the wrapper script is preferred to java -jar because it also passes the JVM flags and the options to load native libraries.

    The deploy jar contains all the classes that would be found by a classloader that searched the classpath from the binary's wrapper script from beginning to end. It also contains the native libraries needed for dependencies. These are automatically loaded into the JVM at runtime.

    If your target specifies a launcher attribute, then instead of being a normal JAR file, the _deploy.jar will be a native binary. This will contain the launcher plus any native (C++) dependencies of your rule, all linked into a static binary. The actual jar file's bytes will be appended to that native binary, creating a single binary blob containing both the executable and the Java code. You can execute the resulting jar file directly like you would execute any native binary.

  • name_deploy-src.jar: An archive containing the sources collected from the transitive closure of the target. These will match the classes in the deploy.jar except where jars have no matching source jar.

A deps attribute is not allowed in a java_binary rule without srcs; such a rule requires a main_class provided by runtime_deps.

The following code snippet illustrates a common mistake:

java_binary(
    name = "DontDoThis",
    srcs = [
        ...,
        "GeneratedJavaFile.java",  # a generated .java file
    ],
    deps = [":generating_rule"],  # rule that generates that file
)

Do this instead:

java_binary(
    name = "DoThisInstead",
    srcs = [
        ...,
        ":generating_rule",
    ],
)

Arguments

Attributes
name

Name; required

A unique name for this target.


It is good practice to use the name of the source file that is the main entry point of the application (minus the extension). For example, if your entry point is called Main.java, then your name could be Main.
deps

List of labels; default is []

The list of other libraries to be linked in to the target. See general comments about deps at Typical attributes defined by most build rules.
srcs

List of labels; default is []

The list of source files that are processed to create the target. This attribute is almost always required; see exceptions below.

Source files of type .java are compiled. In case of generated .java files it is generally advisable to put the generating rule's name here instead of the name of the file itself. This not only improves readability but makes the rule more resilient to future changes: if the generating rule generates different files in the future, you only need to fix one place: the outs of the generating rule. You should not list the generating rule in deps because it is a no-op.

Source files of type .srcjar are unpacked and compiled. (This is useful if you need to generate a set of .java files with a genrule.)

Rules: if the rule (typically genrule or filegroup) generates any of the files listed above, they will be used the same way as described for source files.

This argument is almost always required, except if a main_class attribute specifies a class on the runtime classpath or you specify the runtime_deps argument.

resources

List of labels; default is []

A list of data files to include in a Java jar.

If resources are specified, they will be bundled in the jar along with the usual .class files produced by compilation. The location of the resources inside of the jar file is determined by the project structure. Bazel first looks for Maven's standard directory layout, (a "src" directory followed by a "resources" directory grandchild). If that is not found, Bazel then looks for the topmost directory named "java" or "javatests" (so, for example, if a resource is at <workspace root>/x/java/y/java/z, the path of the resource will be y/java/z. This heuristic cannot be overridden, however, the resource_strip_prefix attribute can be used to specify a specific alternative directory for resource files.

Resources may be source files or generated files.

classpath_resources

List of labels; default is []

DO NOT USE THIS OPTION UNLESS THERE IS NO OTHER WAY)

A list of resources that must be located at the root of the java tree. This attribute's only purpose is to support third-party libraries that require that their resources be found on the classpath as exactly "myconfig.xml". It is only allowed on binaries and not libraries, due to the danger of namespace conflicts.

create_executable

Boolean; nonconfigurable; default is True

Deprecated, use java_single_jar instead.
deploy_env

List of labels; default is []

A list of other java_binary targets which represent the deployment environment for this binary. Set this attribute when building a plugin which will be loaded by another java_binary.
Setting this attribute excludes all dependencies from the runtime classpath (and the deploy jar) of this binary that are shared between this binary and the targets specified in deploy_env.
deploy_manifest_lines

List of strings; default is []

A list of lines to add to the META-INF/manifest.mf file generated for the *_deploy.jar target. The contents of this attribute are not subject to "Make variable" substitution.
javacopts

List of strings; default is []

Extra compiler options for this library. Subject to "Make variable" substitution and Bourne shell tokenization.

These compiler options are passed to javac after the global compiler options.

jvm_flags

List of strings; default is []

A list of flags to embed in the wrapper script generated for running this binary. Subject to $(location) and "Make variable" substitution, and Bourne shell tokenization.

The wrapper script for a Java binary includes a CLASSPATH definition (to find all the dependent jars) and invokes the right Java interpreter. The command line generated by the wrapper script includes the name of the main class followed by a "$@" so you can pass along other arguments after the classname. However, arguments intended for parsing by the JVM must be specified before the classname on the command line. The contents of jvm_flags are added to the wrapper script before the classname is listed.

Note that this attribute has no effect on *_deploy.jar outputs.

launcher

Label; default is None

Specify a binary that will be used to run your Java program instead of the normal bin/java program included with the JDK. The target must be a cc_binary. Any cc_binary that implements the Java Invocation API can be specified as a value for this attribute.

By default, Bazel will use the normal JDK launcher (bin/java or java.exe).

The related --java_launcher Bazel flag affects only those java_binary and java_test targets that have not specified a launcher attribute.

Note that your native (C++, SWIG, JNI) dependencies will be built differently depending on whether you are using the JDK launcher or another launcher:

  • If you are using the normal JDK launcher (the default), native dependencies are built as a shared library named {name}_nativedeps.so, where {name} is the name attribute of this java_binary rule. Unused code is not removed by the linker in this configuration.
  • If you are using any other launcher, native (C++) dependencies are statically linked into a binary named {name}_nativedeps, where {name} is the name attribute of this java_binary rule. In this case, the linker will remove any code it thinks is unused from the resulting binary, which means any C++ code accessed only via JNI may not be linked in unless that cc_library target specifies alwayslink = 1.

When using any launcher other than the default JDK launcher, the format of the *_deploy.jar output changes. See the main java_binary docs for details.

main_class

String; default is ""

Name of class with main() method to use as entry point. If a rule uses this option, it does not need a srcs=[...] list. Thus, with this attribute one can make an executable from a Java library that already contains one or more main() methods.

The value of this attribute is a class name, not a source file. The class must be available at runtime: it may be compiled by this rule (from srcs) or provided by direct or transitive dependencies (through runtime_deps or deps). If the class is unavailable, the binary will fail at runtime; there is no build-time check.

plugins

List of labels; default is []

Java compiler plugins to run at compile-time. Every java_plugin specified in this attribute will be run whenever this rule is built. A library may also inherit plugins from dependencies that use exported_plugins. Resources generated by the plugin will be included in the resulting jar of this rule.
resource_jars

List of labels; default is []

Deprecated: Use java_import and deps or runtime_deps instead.
resource_strip_prefix

String; default is ""

The path prefix to strip from Java resources.

If specified, this path prefix is stripped from every file in the resources attribute. It is an error for a resource file not to be under this directory. If not specified (the default), the path of resource file is determined according to the same logic as the Java package of source files. For example, a source file at stuff/java/foo/bar/a.txt will be located at foo/bar/a.txt.

runtime_deps

List of labels; default is []

Libraries to make available to the final binary or test at runtime only. Like ordinary deps, these will appear on the runtime classpath, but unlike them, not on the compile-time classpath. Dependencies needed only at runtime should be listed here. Dependency-analysis tools should ignore targets that appear in both runtime_deps and deps.
stamp

Integer; default is -1

Whether to encode build information into the binary. Possible values:
  • stamp = 1: Always stamp the build information into the binary, even in --nostamp builds. This setting should be avoided, since it potentially kills remote caching for the binary and any downstream actions that depend on it.
  • stamp = 0: Always replace build information by constant values. This gives good build result caching.
  • stamp = -1: Embedding of build information is controlled by the --[no]stamp flag.

Stamped binaries are not rebuilt unless their dependencies change.

use_launcher

Boolean; default is True

Whether the binary should use a custom launcher.

If this attribute is set to false, the launcher attribute and the related --java_launcher flag will be ignored for this target.

use_testrunner

Boolean; default is False

Use the test runner (by default com.google.testing.junit.runner.BazelTestRunner) class as the main entry point for a Java program, and provide the test class to the test runner as a value of bazel.test_suite system property. You can use this to override the default behavior, which is to use test runner for java_test rules, and not use it for java_binary rules. It is unlikely you will want to do this. One use is for AllTest rules that are invoked by another rule (to set up a database before running the tests, for example). The AllTest rule must be declared as a java_binary, but should still use the test runner as its main entry point. The name of a test runner class can be overridden with main_class attribute.

java_lite_proto_library

View rule source
java_lite_proto_library(name, deps, compatible_with, deprecation, distribs, exec_compatible_with, exec_properties, features, restricted_to, tags, target_compatible_with, testonly, toolchains, visibility)

java_lite_proto_library generates Java code from .proto files.

deps must point to proto_library rules.

Example:


java_library(
    name = "lib",
    runtime_deps = [":foo"],
)

java_lite_proto_library(
    name = "foo",
    deps = [":bar"],
)

proto_library(
    name = "bar",
)

Arguments

Attributes
name

Name; required

A unique name for this target.

deps

List of labels; default is []

The list of proto_library rules to generate Java code for.

java_proto_library

View rule source
java_proto_library(name, deps, compatible_with, deprecation, distribs, exec_compatible_with, exec_properties, features, licenses, restricted_to, tags, target_compatible_with, testonly, toolchains, visibility)

java_proto_library generates Java code from .proto files.

deps must point to proto_library rules.

Example:


java_library(
    name = "lib",
    runtime_deps = [":foo_java_proto"],
)

java_proto_library(
    name = "foo_java_proto",
    deps = [":foo_proto"],
)

proto_library(
    name = "foo_proto",
)

Arguments

Attributes
name

Name; required

A unique name for this target.

deps

List of labels; default is []

The list of proto_library rules to generate Java code for.