Debian Codegraph @

java_comparison/README.md

raw
1 Jsonnet to Java
2 ---------------
3
4 This little code example shows how a Jsonnet config using object-oriented features can be
5 transliterated (in a structure-preserving manner) to use the object-oriented features of Java. Not
6 all Jsonnet programs can be converted to Java because Jsonnet has mixins and virtual inner classes.
7 Execution order is also different, as Jsonnet is lazy and Java is eager. Likewise, Java programs
8 cannot all be converted to Jsonnet because they have mutable state and I/O.
9
10 However said all this, there is a significant overlap between the two languages. This example fits
11 within that overlap.
12
13
14 Execute Jsonnet code
15 --------------------
16
17 ```
18 jsonnet sub-template.jsonnet
19 ```
20
21
22 Execute Java code
23 -----------------
24
25 We pipe into jsonnet - to pretty-print the output JSON.
26
27 ```
28 javac *.java && java Test | jsonnet -
29 ```
30
31
32 Structure of Java code
33 ----------------------
34
35 The translation is as as follows:
36
37 * Everything is typed as Object, as Jsonnet is dynamically typed. Everything is public, as is implicit in Jsonnet.
38 * Jsonnet arrays are Object[], and primitives are Boolean / Double / String.
39 * Jsonnet objects are singleton instances of named Java classes that extend JsonnetObject.
40 * Jsonnet fields become Java methods with no parameters (fields are virtual in Jsonnet).
41 * Jsonnet hidden field status is represented with a method nonHiddenFields which returns a set of
42 field names. Other fields are considered hidden.
43 * There are 2 liberties taken -- output strings are not escaped properly, and the JSON is printed on
44 a single line instead of pretty-printed with indenting.
45
46 The Java code has a number of auxiliary framework functions to provide Jsonnet functionality that is
47 implicit in the Jsonnet language.
48
49 * The Test class chooses an object and manifests it to stdout.
50 * The JsonnetValue class implements manifestation, as a visitor over possible JSON values that
51 builds JSON strings. For objects, it iterates over the non-hidden fields and manifests each value
52 by reflectively calling that function.
53
54
55 Reference JSON
56 --------------
57
58 For reference, the JSON that should be output is given in sub-template.json