简体   繁体   中英

Java define class members by a final array

I have an array which contains some definitions which are used in the program:

final String[] names = new String[]{"familyNames", "givenNames", "middleNames", "nickNames", "additionalNames", ..., ..., ..., ...}; // Lots of definitions

And now I need to create a new class with these definitions:

public class Person {
  final private String id;
  final private String familyNames;
  final private String givenNames;
  final private String middleNames;
  final private String nickNames;
  final private String additionalNames;
  ...
  ...
  ...
  ...
  ... // Very long list
}

Is it possible to define this class by that array? Something like:

public class Person {
  final private String id;
  final private .... names...
  public int compareTo(...) {...}
}

This Person class should support sort by multi fields, eg first by given name, then by family name, etc.

To avoid a long list of class member variables, you may use a map of attributes as mentioned here:

Map<String,String> attributesMap = new HashMap<String,String>();

"familyNames", "givenNames", "middleNames", "nickNames", "additionalNames", etc should be used as keys.

You could define it in a class Person by taking the attributesMap in a static factory method.

public class Person {
  final private String id;
  final private Name name;
  ...
  public static Person fromAttributesMap(Map<String, String> attributesMap) {
      Person person = new Person();
      person.id = attributesMap.get("id");
      ...
  }
}

But do keep related attributes together in their own classes. For eg; you could club familyName , givenName , nickName , etc. in a Name class:

class Name {
  final private String familyName;
  final private String givenName;
  final private String middleName;
}

I'm not in full agreement to the map approach. Infact, there is a code smell around the same - it is called "Primitive obsession"

You could also sort a List<Person> , for example by the family name:

public static Comparator<Person> FamilyNameComparator 
                      = new Comparator<Person>() {

    public int compare(Person person1, Person person2) {


      //ascending order
      return person1.getFamilyName().compareTo(person2.getFamilyName());
    }

};

and then calling:

Arrays.sort(persons, Person.FamilyNameComparator);

You could also sort by multiple fields. Take a look at this question on SO.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM