0

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];
  }

} 
Alexander Mills
  • 90,741
  • 139
  • 482
  • 817
  • What do you mean with metadata fields and user defined fields? Java is not a script language and users, whoever they are in this context, can’t just define fields. Besides java has scope, a field in one class doesn’t clash with a field in another class even if they have the same name. – Joakim Danielson Dec 01 '18 at 08:56
  • @JoakimDanielson I think you missed the fact that this question is about code generation - users may define any number of fields. – Sami Hult Dec 01 '18 at 08:58

1 Answers1

1

Java has no notion of symbols the way ES6 has.

If you simply want to "tag" a class, why not consider making the class implement an (possibly empty) interface? Class and interface names are unique.

Sami Hult
  • 3,052
  • 1
  • 12
  • 17