0
Files
android_webview
apps
ash
base
build
build_overrides
buildtools
cc
chrome
chromecast
chromeos
codelabs
components
content
courgette
crypto
dbus
device
docs
accessibility
autofill
design
enterprise
experiments
fuchsia
gpu
images
infra
intl
ios
linux
login
mac
media
memory
memory-infra
patterns
privacy
privacy_budget
process
security
speed
speed_metrics
standards
telemetry_extension
testing
ui
updater
webapps
workflow
DIR_METADATA
OWNERS
README.md
accessibility.md
ad_tagging.md
adding_to_third_party.md
android_accessing_cpp_enums_in_java.md
android_accessing_cpp_features_in_java.md
android_accessing_cpp_switches_in_java.md
android_build_instructions.md
android_cast_build_instructions.md
android_debugging_instructions.md
android_dynamic_feature_modules.md
android_emulator.md
android_isolated_splits.md
android_logging.md
android_native_libraries.md
android_studio.md
angle_in_chromium.md
api_keys.md
asan.md
atom.md
bitmap_pipeline.md
branch_sheriff.md
building_old_revisions.md
callback.md
ccache_mac.md
chrome_os_logging.md
chrome_settings.md
chrome_untrusted.md
chromedriver_status.md
chromeos_build_instructions.md
chromeos_glossary.md
chromium_browser_vs_google_chrome.md
cipd_and_3pp.md
cl_respect.md
clang.md
clang_code_coverage_wrapper.md
clang_format.md
clang_sheriffing.md
clang_static_analyzer.md
clang_tidy.md
clang_tool_refactoring.md
clangd.md
clion.md
closure_compilation.md
cocoa_tips_and_tricks.md
code_review_owners.md
code_reviews.md
commit_checklist.md
component_build.md
configuration.md
contributing.md
cq_quick_run.md
cr_respect.md
cr_user_manual.md
cross_platform_ui.md
cygwin_dll_remapping_failure.md
dangling_ptr.md
dbus_mojo_connection_service.md
debugging_with_crash_keys.md
deterministic_builds.md
disassemble_code.md
documentation_best_practices.md
documentation_guidelines.md
early-hints.md
eclipse.md
emacs.md
erc_irc.md
flag_expiry.md
flag_ownership.md
frame_trees.md
gdbinit.md
get_the_code.md
git_cookbook.md
git_tips.md
google_chrome_branded_builds.md
google_play_services.md
graphical_debugging_aid_chromium_views.md
gwp_asan.md
how_cc_works.md
how_to_add_your_feature_flag.md
how_to_extend_web_test_framework.md
idn.md
initialize_blink_features.md
inlined_stack_traces.md
installation_at_vmware.md
ios_build_instructions.md
ios_infra.md
ios_voiceover.md
kiosk_mode.md
lacros.md
life_of_a_frame.md
lldbinit.md
mac_arm64.md
mac_build_instructions.md
mac_lld.md
mojo_and_services.md
mojo_ipc_conversion.md
mojo_testing.md
native_relocations.md
navbar.md
navigation-request-navigation-state.gv
navigation-request-navigation-state.png
navigation.md
navigation_concepts.md
network_traffic_annotations.md
new_port_policy.md
no_sources_assignment_filter.md
optimizing_web_uis.md
origin_trials_integration.md
ozone_overview.md
parsing_test_results.md
pgo.md
piranha_plant.md
process_model_and_site_isolation.md
profiling.md
profiling_content_shell_on_android.md
proxy_auto_config.md
python3_migration.md
qtcreator.md
release_branch_guidance.md
render-frame-host-lifecycle-state.gv
render-frame-host-lifecycle-state.png
render_document.md
seccomp_sandbox_crash_dumping.md
servicification.md
session_history.md
sheriff.md
shutdown.md
special_case_urls.md
static_initializers.md
sublime_ide.md
system_hardening_features.md
tab_helpers.md
threading_and_tasks.md
threading_and_tasks_faq.md
threading_and_tasks_testing.md
toolchain_support.md
tour_of_luci_ui.md
tpm_quick_ref.md
translation_screenshots.md
trusted_types_on_webui.md
updating_clang.md
updating_clang_format_binaries.md
use_counter_wiki.md
useful_urls.md
user_data_dir.md
user_data_storage.md
user_handle_mapping.md
vanilla_msysgit_workflow.md
vscode.md
vscode_python.md
webui_build_configuration.md
webui_explainer.md
webui_in_chrome.md
webui_in_components.md
webview_policies.md
win_cross.md
win_order_files.md
windows_build_instructions.md
windows_native_window_occlusion_tracking.md
windows_pwa_integration.md
windows_shortcut_and_taskbar_handling.md
windows_split_dll.md
windows_virtual_desktop_handling.md
wmax_tokens.md
working_remotely_with_android.md
writing_clang_plugins.md
extensions
fuchsia_web
gin
google_apis
google_update
gpu
headless
infra
ios
ipc
media
mojo
native_client_sdk
net
pdf
ppapi
printing
remoting
rlz
sandbox
services
skia
sql
storage
styleguide
testing
third_party
tools
ui
url
weblayer
.clang-format
.clang-tidy
.eslintrc.js
.git-blame-ignore-revs
.gitattributes
.gitignore
.gn
.mailmap
.rustfmt.toml
.vpython
.vpython3
.yapfignore
AUTHORS
BUILD.gn
CODE_OF_CONDUCT.md
DEPS
DIR_METADATA
ENG_REVIEW_OWNERS
LICENSE
LICENSE.chromium_os
OWNERS
PRESUBMIT.py
PRESUBMIT_test.py
PRESUBMIT_test_mocks.py
README.md
WATCHLISTS
codereview.settings
src/docs/android_accessing_cpp_enums_in_java.md
Andrew Grieve 048ea3976d Android: Make missing dep suggestions more copy / pasteable
Bug: None
Change-Id: I01b59489312ea1c367f50f3c229ea9396bd8b2fa
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/3457782
Reviewed-by: Peter Wen <wnwen@chromium.org>
Reviewed-by: Sky Malice <skym@chromium.org>
Commit-Queue: Andrew Grieve <agrieve@chromium.org>
Cr-Commit-Position: refs/heads/main@{#970697}
2022-02-14 17:58:54 +00:00

5.8 KiB

Accessing C++ Enums In Java

[TOC]

Introduction

Accessing C++ enums in Java is implemented via a Python script which analyzes the C++ enum and spits out the corresponding Java class. The enum needs to be annotated in a particular way. By default, the generated class name will be the same as the name of the enum. If all the names of the enum values are prefixed with the MACRO_CASED_ name of the enum those prefixes will be stripped from the Java version.

Features

  • Customize the package name of the generated class using the GENERATED_JAVA_ENUM_PACKAGE directive (required)
  • Customize the class name using the GENERATED_JAVA_CLASS_NAME_OVERRIDE directive (optional)
  • Strip enum entry prefixes to make the generated classes less verbose using the GENERATED_JAVA_PREFIX_TO_STRIP directive (optional)
  • Follows best practices by using IntDef Instead of Enum
  • Copies comments that directly precede enum entries into the generated Java class

Usage

  1. Add directives to your C++ enum. Only the GENERATED_JAVA_ENUM_PACKAGE directive is required:

    // GENERATED_JAVA_ENUM_PACKAGE: org.chromium.chrome
    // GENERATED_JAVA_CLASS_NAME_OVERRIDE: FooBar
    // GENERATED_JAVA_PREFIX_TO_STRIP: BAR_
    enum SomeEnum {
      BAR_A,
      BAR_B,
      BAR_C = BAR_B,
    };
    
  2. Add a new build target and add it to the srcjar_deps of an android_library target:

    if (is_android) {
      import("//build/config/android/rules.gni")
    }
    
    if (is_android) {
      java_cpp_enum("java_enum_srcjar") {
        # External code should depend on ":foo_java" instead.
        visibility = [ ":*" ]
        sources = [
          # Include the .h or .cc file(s) which defines the enum(s).
          "base/android/native_foo_header.h",
        ]
      }
    
      # If there's already an android_library target, you can add
      # java_enum_srcjar to that target's srcjar_deps. Otherwise, the best
      # practice is to create a new android_library just for this target.
      android_library("foo_java") {
        srcjar_deps = [ ":java_enum_srcjar" ]
    
        # Important: the generated enum uses the @IntDef annotation provided by
        # this dependency.
        deps = [ "//third_party/androidx:androidx_annotation_annotation_java" ]
      }
    }
    
  3. The generated file org/chromium/chrome/FooBar.java would contain:

    package org.chromium.chrome;
    
    import androidx.annotation.IntDef;
    
    import java.lang.annotation.Retention;
    import java.lang.annotation.RetentionPolicy;
    
    @IntDef({
        FooBar.A, FooBar.B, FooBar.C
    })
    @Retention(RetentionPolicy.SOURCE)
    public @interface FooBar {
      int A = 0;
      int B = 1;
      int C = 1;
    }
    

Formatting Notes

  • Handling long package names:

    // GENERATED_JAVA_ENUM_PACKAGE: (
    //   org.chromium.chrome.this.package.is.too.long.to.fit.on.a.single.line)
    
  • Enum entries

    • Single line enums should look like this:

      // GENERATED_JAVA_ENUM_PACKAGE: org.foo
      enum NotificationActionType { BUTTON, TEXT };
      
    • Multi-line enums should have one enum entry per line, like this:

      // GENERATED_JAVA_ENUM_PACKAGE: org.foo
      enum NotificationActionType {
        BUTTON,
        TEXT
      };
      
    • Multi-line enum entries are allowed but should be formatted like this:

      // GENERATED_JAVA_ENUM_PACKAGE: org.foo
      enum NotificationActionType {
        LongKeyNumberOne,
        LongKeyNumberTwo,
        ...
        LongKeyNumberThree =
            LongKeyNumberOne | LongKeyNumberTwo | ...
      };
      
  • Preserving comments

    // GENERATED_JAVA_ENUM_PACKAGE: org.chromium
    enum CommentEnum {
      // This comment will be preserved.
      ONE,
      TWO, // This comment will NOT be preserved.
      THREE
    }
    
    ...
    public @interface CommentEnum {
      ...
      /**
       * This comment will be preserved.
       */
      int ONE = 0;
      int TWO = 1;
      int THREE = 2;
    }
    

Troubleshooting

Symbol not found/could not resolve IntDef

You may see an error like this when compiling:

$ autoninja -C out/Default base/foo_java
util.build_utils.CalledProcessError: Command failed: ...
org/chromium/chrome/FooBar.java:13: error: symbol not found androidx.annotation.IntDef
Hint: Add "//third_party/androidx:androidx_annotation_annotation_java" to deps of //base/foo_java
import androidx.annotation.IntDef;
       ^
org/chromium/chrome/FooBar.java:18: error: could not resolve IntDef
@IntDef({
^

The fix is to add "//third_party/androidx:androidx_annotation_annotation_java" to the deps of the android_library. Note: do not add this to the java_cpp_enum target by mistake, otherwise you'll see a new error:

$ autoninja -C out/Default base/foo_java
[0/1] Regenerating ninja files
ERROR at //base/BUILD.gn:194:12: Assignment had no effect.
    deps = [ "//third_party/androidx:androidx_annotation_annotation_java" ]
           ^--------------------------------------------------------------
You set the variable "deps" here and it was unused before it went
out of scope.
...

See also

Code