tarmogoyf

Enums

Oct 26th, 2023
787
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.93 KB | Source Code | 0 0
  1.  
  2. public final class Color {
  3.     //
  4.     private static final List<Color> colors = new ArrayList<>();
  5.     public static final Color RED = new Color();
  6.     public static final Color GREEN = new Color();
  7.     private final int ordinal;
  8.     private final String name;
  9.  
  10.     private Color() {
  11.         this.ordinal = colors == null ? 0 : colors.size();
  12.         this.name = Arrays.stream(this.getClass().getDeclaredFields()).filter(f -> f.getType()==Color.class).filter(f -> {
  13.                     try {
  14.                         return f.get(this) == this;
  15.                     } catch (IllegalAccessException e) {
  16.                         e.printStackTrace();
  17.                     }
  18.                     return false;
  19.                 }).map(Field::getName).findFirst().orElseThrow();
  20.  
  21.         colors.add(this);
  22.     }
  23.  
  24.     public int getOrdinal() {
  25.         return ordinal;
  26.     }
  27.  
  28.     public String getName() {
  29.         return name;
  30.     }
  31. }
  32.  
Advertisement
Add Comment
Please, Sign In to add comment