Do String Resource Xml Files Allow Invalid Java Variables As Name Attributes?
Solution 1:
It is not possible. Xml files are parsed and the static class R is generated and, in order to compile, the class has to contain valid members name.
Solution 2:
I'm answering my own question because although the advice here about best practice is valid, it was not best practice that I asked about.
The answer is that although the string named "hello.world" would be an invalid Java variable, it is permitted in the XML as the build process automatically converts the "." symbol to an underscore before it becomes a Java class member variable.
The following strings:
<string name="foo_bar"> .. </string>
<string name="foo.baz"> .. </string>
Will produce (whether due to a feature or a bug) members in R.java as follows:
publicstaticfinalclassstring {
publicstaticfinalint foo_bar=0x7f0a000f; // <- validpublicstaticfinalint foo_baz=0x7f0a0010; // <- valid (CONVERTED)
}
The following two strings however:
<string name="foo_bar"> .. </string>
<string name="foo.bar"> .. </string>
Will result in a collision and the build process will fail:
publicstaticfinalclassstring {
publicstaticfinalint foo_bar=0x7f0a000f; // <- validpublicstaticfinalint foo_bar=0x7f0a0010; // <- DUPLICATE
}
The following strings:
<string name="foo bar"> .. </string>
<string name="foo-baz"> .. </string>
<string name="42foo"> .. </string>
Will break the build process producing invalid members in R.java as follows:
publicstaticfinalclassstring {
publicstaticfinalint42foo=0x7f0a0000; // <- invalidpublicstaticfinalint foo bar=0x7f0a000f; // <- invalidpublicstaticfinalint foo-baz=0x7f0a0010; // <- invalid
}
I verified these by building a project via Android Studio and also via the command line Gradle program. The "." => "_" conversion appears to be a one-off (although I only tried a few common punctuations as shown above.
TL;DR Names should be valid Java variables, but the XML format and build process will automatically convert "." symbols adding the risk of key collisions.
Post a Comment for "Do String Resource Xml Files Allow Invalid Java Variables As Name Attributes?"