I have a library, I have to tag a class with certain field dynamically (code generation) and I don't want the meta-data field names I generate to clash with user-defined field names.
Using JavaScript, we can use ES6 Symbols to do this. We can create getters/setters and retrieve fields using Symbols and in this way prevent name-clashing.
So using JS, it might look like:
export class Foo {
static libraryDefinedField = Symbol('lib.defined')
userDefinedField = 'whatev';
setLibraryDefinedField(v){
this[Foo.libraryDefinedField] = v;
}
getLibraryDefinedField(v){
return this[Foo.libraryDefinedField];
}
}
is there a way to do this with Java somehow - create instance or static fields on a class that won't conflict with user-defined fields?
Note that using JS, if there were user-generated static field properties and we wanted to prevent nameclashing, we might do this:
// put the symbol outside the class, so even static properties won't conflict
const libraryDefinedField = Symbol('lib.defined');
export class Foo {
userDefinedField = 'whatev';
setLibraryDefinedField(v){
this[libraryDefinedField] = v;
}
getLibraryDefinedField(v){
return this[libraryDefinedField];
}
}