Information in Android Studio Flamingo



Posted by Clément Béra, Senior software program engineer

Information are a brand new Java characteristic for immutable information service courses launched in Java 16 and Android 14. To make use of data in Android Studio Flamingo, you want an Android 14 (API stage 34) SDK so the java.lang.Report class is in android.jar. That is out there from the “Android UpsideDownCake Preview” SDK revision 4. Information are basically courses with immutable properties and implicit hashCode, equals, and toString strategies primarily based on the underlying information fields. In that respect they’re similar to Kotlin information courses. To declare a Particular person document with the fields String identify and int age to be compiled to a Java document, use the next code:

@JvmRecord
information class Particular person(val identify: String, val age: Int)

The construct.gradle file additionally must be prolonged to make use of the right SDK and Java supply and goal. At the moment the Android UpsideDownCake Preview is required, however when the Android 14 last SDK is launched use “compileSdk 34” and “targetSdk 34” rather than the preview model.

android {
compileSdkPreview "UpsideDownCake"

defaultConfig {
targetSdkPreview "UpsideDownCake"
}

compileOptions {
sourceCompatibility JavaVersion.VERSION_17
targetCompatibility JavaVersion.VERSION_17
}
kotlinOptions {
jvmTarget = '17'
}
}

Information don’t essentially carry worth in comparison with information courses in pure Kotlin packages, however they let Kotlin packages work together with Java libraries whose APIs embody data. For Java programmers this permits Java code to make use of data. Use the next code to declare the identical document in Java:

public document Particular person(String identify, int age) {}

Apart from the document flags and attributes, the document Particular person is roughly equal to the next class described utilizing Kotlin supply:

class PersonEquivalent(val identify: String, val age: Int) {

override enjoyable hashCode() : Int {
return 31
* (31 * PersonEquivalent::class.hashCode()
+ identify.hashCode())
+ Integer.hashCode(age)
}

override enjoyable equals(different: Any?) : Boolean {
if (different == null || different !is PersonEquivalent) {
return false
}
return identify == different.identify && age == different.age
}

override enjoyable toString() : String {
return String.format(
PersonEquivalent::class.java.simpleName + "[name=%s, age=%s]",
identify,
age.toString()
)
}
}

println(Particular person(“John”, 42).toString())
>>> Particular person[name=John, age=42]

It’s doable in a document class to override the hashCode, equals, and toString strategies, successfully changing the JVM runtime generated strategies. On this case, the conduct is user-defined for these strategies.

Report desugaring

Since data are usually not supported on any Android gadget in the present day, the D8/R8 desugaring engine must desugar data: it transforms the document code into code suitable with the Android VMs. Report desugaring includes reworking the document right into a roughly equal class, with out producing or compiling sources. The next Kotlin supply reveals an approximation of the generated code. For the applying code dimension to stay small, data are desugared in order that helper strategies are shared in between data.

class PersonDesugared(val identify: String, val age: Int) {
enjoyable getFieldsAsObjects(): Array<Any> {
return arrayOf(identify, age)
}

override enjoyable hashCode(): Int {
return SharedRecordHelper.hash(
PersonDesugared::class.java,
getFieldsAsObjects())
}

override enjoyable equals(different: Any?): Boolean {
if (different == null || different !is PersonDesugared) {
return false
}
return getFieldsAsObjects().contentEquals(different.getFieldsAsObjects())
}

override enjoyable toString(): String {
return SharedRecordHelper.toString(
getFieldsAsObjects(),
PersonDesugared::class.java,
"identify;age")
}

class SharedRecordHelper {
companion object {
enjoyable hash(recordClass: Class<*>, fieldValues: Array<Any>): Int {
return 31 * recordClass.hashCode() + fieldValues.contentHashCode()
}

enjoyable toString(
fieldValues: Array<Any>,
recordClass: Class<*>,
fieldNames: String
)
: String {
val fieldNamesSplit: Checklist<String> =
if (fieldNames.isEmpty()) emptyList() else fieldNames.break up(";")
val builder: StringBuilder = StringBuilder()
builder.append(recordClass.simpleName).append("[")
for (i in fieldNamesSplit.indices) {
builder
.append(fieldNamesSplit[i])
.append("=")
.append(fieldValues[i])
if (i != fieldNamesSplit.dimension - 1) {
builder.append(", ")
}
}
builder.append("]")
return builder.toString()
}
}
}
}

Report shrinking

R8 assumes that the default hashCode, equals, and toString strategies generated by javac successfully signify the inner state of the document. Due to this fact, if a area is minified, the strategies ought to mirror that; toString ought to print the minified identify. If a area is eliminated, for instance as a result of it has a relentless worth throughout all cases, then the strategies ought to mirror that; the sector is ignored by the hashCode, equals, and toString strategies. When R8 makes use of the document construction within the strategies generated by javac, for instance when it seems up fields within the document or inspects the printed document construction, it is utilizing reflection. As is the case for any use of reflection, you have to write maintain guidelines to tell the shrinker of the reflective use in order that it may well protect the construction.

In our instance, assume that age is the fixed 42 throughout the applying whereas identify isn’t fixed throughout the applying. Then toString returns completely different outcomes relying on the principles you set:

Particular person(“John”, 42).toString();

>>> Particular person[name=John, age=42]

>>> a[a=John]

>>> Particular person[b=John]

>>> a[name=John]

>>> a[a=John, b=42]

>>> Particular person[name=John, age=42]

Reflective use instances

Protect toString conduct

Say you’ve gotten code that makes use of the precise printing of the document and expects it to be unchanged. For that you have to maintain the total content material of the document fields with a rule reminiscent of:

-keep,allowshrinking class Particular person
-keepclassmembers,allowoptimization class Particular person { <fields>; }

This ensures that if the Particular person document is retained within the output, any toString callproduces the very same string as it will within the authentic program. For instance:

Particular person("John", 42).toString();
>>> Particular person[name=John, age=42]

Nevertheless, should you solely wish to protect the printing for the fields which are really used, you may let the unused fields to be eliminated or shrunk with allowshrinking:

-keep,allowshrinking class Particular person
-keepclassmembers,allowshrinking,allowoptimization class Particular person { <fields>; }

With this rule, the compiler drops the age area:

Particular person("John", 42).toString();
>>> Particular person[name=John]

Protect document members for reflective lookup

If you have to reflectively entry a document member, you sometimes have to entry its accessor methodology. For that you have to maintain the accessor methodology:

-keep,allowshrinking class Particular person
-keepclassmembers,allowoptimization class Particular person { java.lang.String identify(); }

Now if cases of Particular person are within the residual program you may safely search for the existence of the accessor reflectively:

Particular person("John", 42)::class.java.getDeclaredMethod("identify").invoke(obj);
>>> John

Discover that the earlier code accesses the document area utilizing the accessor. For direct area entry, you have to maintain the sector itself:

-keep,allowshrinking class Particular person
-keepclassmembers,allowoptimization class Particular person { java.lang.String identify; }

Construct techniques and the Report class

When you’re utilizing one other construct system than AGP, utilizing data could require you to adapt the construct system. The java.lang.Report class just isn’t current till Android 14, launched within the SDK from “Android UpsideDownCake Preview” revision 4. D8/R8 introduces the com.android.instruments.r8.RecordTag, an empty class, to point {that a} document subclass is a document. The RecordTag is used in order that directions referencing java.lang.Report can immediately be rewritten by desugaring to reference RecordTag and nonetheless work (instanceof, methodology and area signatures, and so on.).

Because of this every construct containing a reference to java.lang.Report generates an artificial RecordTag class. In a state of affairs the place an software is break up in shards, every shard being compiled to a dex file, and the dex information put collectively with out merging within the Android software, this might result in duplicate RecordTag class.

To keep away from the problem, any D8 intermediate construct generates the RecordTag class as a worldwide artificial, in a distinct output than the dex file. The dex merge step is then in a position to accurately merge world synthetics to keep away from sudden runtime conduct. Every construct system utilizing a number of compilation reminiscent of sharding or intermediate outputs is required to help world synthetics to work accurately. AGP absolutely helps data from model 8.1.

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles