0
Files
src/docs/android_accessing_cpp_switches_in_java.md
Ian Vollick b99472e9d4 Share strings between native and Java
Creates a script that can be used to generate Java files to
expose native strings to Java, giving us a single source of
truth for these constants.

Bug: 937280
Change-Id: I1f0804bdfff8101dfd149612acd44360ae0dc2c0
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1495747
Commit-Queue: Ian Vollick <vollick@chromium.org>
Auto-Submit: Ian Vollick <vollick@chromium.org>
Reviewed-by: Scott Violet <sky@chromium.org>
Reviewed-by: Andrew Grieve <agrieve@chromium.org>
Cr-Commit-Position: refs/heads/master@{#638754}
2019-03-07 21:35:26 +00:00

2.2 KiB

Accessing C++ Switches In Java

[TOC]

Introduction

Accessing C++ switches in Java is implemented via a Python script which analyzes the C++ switches file and spits out the corresponding Java class. The generated class name will be based upon the switch file name, and the path must be specified in a comment within the switch file itself.

Usage

  1. Add directives to your C++ switch file

    // GENERATED_JAVA_PACKAGE: org.chromium.chrome
    
    // ...snip...
    
    // Documentation for the following switch.
    const char kSomeSwitch[] = "some-switch";
    
    // ...snip...
    
  2. Create a template file

     // Copyright {YEAR} The Chromium Authors. All rights reserved.
     // Use of this source code is governed by a BSD-style license that can be
     // found in the LICENSE file.
    
     // This file is autogenerated by
     //     {SCRIPT_NAME}
     // From
     //     {SOURCE_PATH}, and
     //     {TEMPLATE_PATH}
    
     package my.java.package
    
     // Be sure to escape any curly braces in your template by doubling as
     // follows.
     public abstract class MySwitches {{
    
     {NATIVE_SWITCHES}
    
     }}
    
  3. Add a new build target

    import("//build/config/android/rules.gni")
    
    java_cpp_strings("foo_generated_switch") {
      sources = [
        "//base/android/native_foo_switches.cc",
      ]
      template = "//base/android/java_templates/MySwitches.java.tmpl"
    }
    
  4. Add the new target to the desired android_library targets srcjar_deps:

    android_library("base_java") {
      srcjar_deps = [
        ":foo_generated_switches",
      ]
    }
    
  5. The generated file org/chromium/chrome/NativeFooSwitches.java would contain:

    package org.chromium.chrome;
    
    public final class NativeFooSwitches {
        // ...snip...
    
        public static final String SOME_SWITCH = "some-switch";
    
        // ...snip...
    }
    

Code