引子:一个看似说不通的枚举类型
我们先看一段能正常编译、运行的代码 ⬇️
1public enum Operation { 2 PLUS { 3 double eval(double x, double y) { 4 return x + y; 5 } 6 }, 7 MINUS { 8 double eval(double x, double y) { 9 return x - y; 10 } 11 }, 12 TIMES { 13 double eval(double x, double y) { 14 return x * y; 15 } 16 }, 17 DIVIDED_BY { 18 double eval(double x, double y) { 19 return x / y; 20 } 21 }; 22 23 abstract double eval(double x, double y); 24 25 public static void main(String[] args) { 26 System.out.println(PLUS.eval(1, 2)); 27 System.out.println(PLUS.getClass().getName()); 28 } 29} 30
请将以上代码保存为 Operation.java。通过执行以下命令可以编译 Operation.java 并运行其中的 main 方法。
1javac Operation.java 2java Operation 3
输出如下
13.0 2Operation$1 3
Operation.PLUS.eval(1, 2) 返回 3.0。但似乎有两处说不通:
eval在枚举类里只有声明、没有实现,实现写到了哪里?- 枚举类不能
new,也不像普通抽象类那样能随手继承,那么实现类在哪里?
JDK 里留了一条线索。Enum.getDeclaringClass() 的注释(我参考的是 JDK 21 中的 Enum.java)写着 ⬇️
这个方法的代码只有几行 ⬇️
1@SuppressWarnings("unchecked") 2public final Class<E> getDeclaringClass() { 3 Class<?> clazz = getClass(); 4 Class<?> zuper = clazz.getSuperclass(); 5 return (zuper == Enum.class) ? (Class<E>)clazz : (Class<E>)zuper; 6} 7
也就是说:有些常量的运行时类并不是枚举类本身,而是枚举类的子类。JLS §8.9.1 说得更直接 ⬇️
The optional class body of an enum constant implicitly defines an anonymous class declaration (§15.9.5) that extends the immediately enclosing enum type.
Operation.java 中各个常量后面那段 { ... } 就表明了每个常量都是匿名子类,抽象方法的实现正写在里面。本篇用一个 GUI 小工具把"枚举类 → 常量 → 常量的运行时类"三层摆在一起,并逐一对照 getClass() 与 getDeclaringClass() 的结果。
注意事项
- 完整代码用到了
record和文本块,需要JDK 16+(写作本文时,我使用的是JDK 21) - 只用到公开
API,不需要--add-opens:GUI 代码只用getClass()、getDeclaringClass()、isAnonymousClass()(以及getName()、getSimpleName()、getCanonicalName());正文的反射旁证另外用到了isSealed()、getPermittedSubclasses()、getModifiers()、getDeclaredMethods(),同样不涉及私有成员。getSuperclass()则只出现在Enum.getDeclaringClass()的实现里 Operation$1这类名字是javac的实现细节。GUI的类图下方也有一条提示:工具里显示的是本机javac的编号结果,换编译器可能会不同
正文
我借助 trae 生成了可以对照"枚举源码 / 常量 / 运行时类"的 GUI 代码。为了行文连贯,我把完整的代码放到 完整代码 这一小节里了。
如何运行
请将 完整代码 保存为 EnumTypeGuiDemo.java。使用如下命令可以编译它。
1javac EnumTypeGuiDemo.java 2
编译之后,会得到以下 class 文件 ⬇️
EnumTypeGuiDemo.classEnumTypeGuiDemo$1.class(界面里匿名DefaultTableModel,与枚举无关)EnumTypeGuiDemo$Sample.class、EnumTypeGuiDemo$FactRenderer.class、EnumTypeGuiDemo$HierarchyPanel.classEnumTypeGuiDemo$Direction.classEnumTypeGuiDemo$Operation.class、EnumTypeGuiDemo$Operation$1.class~EnumTypeGuiDemo$Operation$4.classEnumTypeGuiDemo$OrderStatus.class、EnumTypeGuiDemo$OrderStatus$1.class~EnumTypeGuiDemo$OrderStatus$3.class
其中 EnumTypeGuiDemo$Operation$1 ~ EnumTypeGuiDemo$Operation$4 与 EnumTypeGuiDemo$OrderStatus$1 ~ EnumTypeGuiDemo$OrderStatus$3 是本篇的主角:由常量类体生成的匿名子类。这些名字不是规范的一部分:上面的 class 文件列表是我本地 javac 的编译结果,换一个编译器得到的 class 文件的名称也许会不同。本文以及 GUI 工具里展示的所有 $1、$2,都只是"某一种编译器编译出来的样子",阅读时我们关注的是"存在这些子类",而不关心它们具体叫什么。
使用如下命令,可以运行 EnumTypeGuiDemo 中的 main 方法。
1java EnumTypeGuiDemo 2
启动后窗口标题是 enum constant type explorer
界面一览
窗口分成三栏 ⬇️
- 左栏
sample (enum type):三个枚举样例;constants (values()):按values()的顺序排列,也就是声明顺序 - 中栏
runtime class hierarchy (computed from getSuperclass()) - 右栏:一行摘要,9 行
check / result,以及enum source——当前样例的枚举源码,选中常量时加粗并加浅蓝底色,方便查看源码里有没有类体
三个样例正好覆盖以下三种情况
- 全都没有类体
- 全都有类体
- 部分有类体
样例一:所有常量都没有类体
Direction 是最普通的写法 ⬇️
1enum Direction { 2 EAST, WEST, SOUTH, NORTH 3} 4
选中 EAST,右栏九行 ⬇️
| check | result |
|---|---|
| name() | EAST |
| getClass().getName() | EnumTypeGuiDemo$Direction |
| getClass().getSimpleName() | Direction |
| getClass().getCanonicalName() | EnumTypeGuiDemo.Direction |
| getClass().isAnonymousClass() | false |
| getDeclaringClass().getName() | EnumTypeGuiDemo$Direction |
| has class body | no |
| getClass() == E.class | ✔ true |
| getDeclaringClass() == E.class | ✔ true |
getClass() 与 getDeclaringClass() 完全一致。类图里只有一个方框,下方用一行绿字说明 ⬇️
1every constant is a plain instance of Direction - no subclasses were generated 2
补一条反射层面的旁证:Direction.class.isSealed() 返回 false——没有常量带类体,枚举类也就没有"隐含的密封子类"。
样例二:每个常量都有类体
Operation 的四个常量都带类体,各自实现 eval。截图里选中的是 TIMES ⬇️
摘要行:4 个常量、4 个带类体、5 个 class 文件(枚举类 1 个 + 匿名子类 4 个)。
右栏九行(以 TIMES 为例)⬇️
| check | result |
|---|---|
| name() | TIMES |
| getClass().getName() | EnumTypeGuiDemo$Operation$3 |
| getClass().getSimpleName() | (empty string) |
| getClass().getCanonicalName() | null (anonymous class) |
| getClass().isAnonymousClass() | true |
| getDeclaringClass().getName() | EnumTypeGuiDemo$Operation |
| has class body | yes |
| getClass() == E.class | ✘ false |
| getDeclaringClass() == E.class | ✔ true |
getClass() 指向 Operation$3,getDeclaringClass() 却回到 Operation。这正好对应 Enum.getDeclaringClass() 那段实现:如果父类不是 java.lang.Enum,就取父类。
执行 javap -p EnumTypeGuiDemo\$Operation\$3 命令可以看到对应的结构(-p 让私有构造器也显示出来)⬇️
1Compiled from "EnumTypeGuiDemo.java" 2final class EnumTypeGuiDemo$Operation$3 extends EnumTypeGuiDemo$Operation { 3 private EnumTypeGuiDemo$Operation$3(java.lang.String, int); 4 double eval(double, double); 5} 6
而枚举类本身被编译成了抽象类 ⬇️
1Compiled from "EnumTypeGuiDemo.java" 2abstract class EnumTypeGuiDemo$Operation extends java.lang.Enum<EnumTypeGuiDemo$Operation> { 3 public static final EnumTypeGuiDemo$Operation PLUS; 4 public static final EnumTypeGuiDemo$Operation MINUS; 5 public static final EnumTypeGuiDemo$Operation TIMES; 6 public static final EnumTypeGuiDemo$Operation DIVIDED_BY; 7 private static final EnumTypeGuiDemo$Operation[] $VALUES; 8 public static EnumTypeGuiDemo$Operation[] values(); 9 public static EnumTypeGuiDemo$Operation valueOf(java.lang.String); 10 private EnumTypeGuiDemo$Operation(); 11 abstract double eval(double, double); 12 private static EnumTypeGuiDemo$Operation[] $values(); 13 static {}; 14} 15
abstract 这个修饰符也能用反射验证:Modifier.isAbstract(Operation.class.getModifiers()) 返回 true。
如果有常量漏了实现,编译会失败。把 MINUS 改成没有类体 ⬇️
1enum Operation { 2 PLUS { double eval(double x, double y) { return x + y; } }, 3 MINUS; 4 5 abstract double eval(double x, double y); 6} 7
javac 的报错会指向 MINUS(JDK 21,中文语言环境)⬇️
1Operation.java:3: 错误: Operation是抽象的; 无法实例化 2 MINUS; 3 ^ 41 个错误 5
JLS §8.9.2 中有如下内容 ⬇️
It is a compile-time error if an enum declaration E has an
abstractmethodmas a member, unless E has at least one enum constant and all of E's enum constants have class bodies that provide concrete implementations ofm.
样例三:只有部分常量有类体
OrderStatus 是更接近业务的写法:只有终态需要自己的行为,另外还留了一个空类体的常量 ⬇️
1enum OrderStatus { 2 CREATED, 3 PAID, 4 SHIPPED, 5 // { } alone still produces a subclass 6 ON_HOLD { }, 7 COMPLETED { 8 @Override 9 boolean isTerminal() { return true; } 10 }, 11 CANCELLED { 12 @Override 13 boolean isTerminal() { return true; } 14 }; 15 16 boolean isTerminal() { return false; } 17} 18
界面把三类常量都放进同一张图 ⬇️
- 作为根节点的
OrderStatus方框上有CREATED, PAID, SHIPPED,它们的getClass()就是枚举类 ON_HOLD、COMPLETED、CANCELLED各占一个匿名子类框 ⬇️OrderStatus$1OrderStatus$2OrderStatus$3
选中 ON_HOLD,右栏的 has class body 是 yes,getClass() == E.class 是 ✘ false。虽然这个类体里什么都没有,执行 javap -p EnumTypeGuiDemo\$OrderStatus\$1 命令可以看到它只有一个构造器 ⬇️
1Compiled from "EnumTypeGuiDemo.java" 2final class EnumTypeGuiDemo$OrderStatus$1 extends EnumTypeGuiDemo$OrderStatus { 3 private EnumTypeGuiDemo$OrderStatus$1(java.lang.String, int); 4} 5
反射也能印证:OrderStatus$1 的 getDeclaredMethods().length 是 0,而实现了 isTerminal() 的 OrderStatus$2 是 1 ⬇️
1EnumTypeGuiDemo$OrderStatus$1 declared methods = 0 -> [] 2EnumTypeGuiDemo$OrderStatus$2 declared methods = 1 -> [boolean EnumTypeGuiDemo$OrderStatus$2.isTerminal()] 3
也就是说,空类体什么方法都没写,但"它有自己的类"这件事已经发生了。所以此时 getClass() 不等于枚举类。
选中终态 COMPLETED 时,类图高亮的是 OrderStatus$2 ⬇️
值得注意的是,getDeclaringClass() 在这六种情况下都返回 OrderStatus,检查表最后一行始终是 ✔ true。
再补一条:只要有一个常量带类体,枚举类就是隐含 sealed 的。OrderStatus.class.isSealed() 返回 true,getPermittedSubclasses() 正好列出三个匿名子类 ⬇️
1[class EnumTypeGuiDemo$OrderStatus$1, class EnumTypeGuiDemo$OrderStatus$2, class EnumTypeGuiDemo$OrderStatus$3] 2
JLS §8.9 的说法是:
- An enum class E is implicitly
sealedif its declaration contains at least one enum constant that has a class body. The permitted direct subclasses (§8.1.6) of E are the anonymous classes implicitly declared by the enum constants that have a class body.
为什么枚举类中可以定义抽象方法
把上面三个样例汇总,规则可以拆成三条:
- 抽象方法的例外(JLS §8.4.3):普通类里,抽象方法必须写在抽象类中;JLS 为枚举声明单独开了例外——
The declaration of an abstract method m must appear directly within an abstract class (call it A) unless it occurs within an enum declaration.
- 常量类体就是匿名子类(JLS §8.9.1):
The optional class body of an enum constant implicitly declares an anonymous class that is a direct subclass of the immediately enclosing enum class, and is final.
- 必须全部有实现(JLS §8.9.2):
It is a compile-time error if an enum declaration E has an abstract method m as a member, unless E has at least one enum constant and all of E's enum constants have class bodies that provide concrete implementations of m.
合起来就是:抽象方法由"常量的匿名子类"实现,枚举类自己不需要实现,所以编译器允许这组声明存在。
编译器具体做了三件事,javap -c 里的 static {} 可以看到 ⬇️
1static {}; 2 Code: 3 0: new #35 // class EnumTypeGuiDemo$Operation$1 4 3: dup 5 4: ldc #37 // String PLUS 6 6: iconst_0 7 7: invokespecial #38 // Method EnumTypeGuiDemo$Operation$1."<init>":(Ljava/lang/String;I)V 8 10: putstatic #3 // Field PLUS:LEnumTypeGuiDemo$Operation; 9 13: new #39 // class EnumTypeGuiDemo$Operation$2 10 16: dup 11 17: ldc #41 // String MINUS 12 19: iconst_1 13 20: invokespecial #42 // Method EnumTypeGuiDemo$Operation$2."<init>":(Ljava/lang/String;I)V 14 23: putstatic #7 // Field MINUS:LEnumTypeGuiDemo$Operation; 15 ... 16
- 声明了抽象方法的枚举类被标记为
abstract(OrderStatus没有抽象方法,就没有这个修饰符,Modifier.isAbstract分别返回true/false) - 每个带类体的常量,
new的是对应的匿名子类;("PLUS", 0)里的0就是 ordinal - 所有实例放进
$VALUES,values()再对外返回
所以 Operation.PLUS.eval(1, 2) 的真正接收者是 Operation$1,而不是 Operation。静态字段 PLUS 的类型仍然是 Operation,多态在这里照常生效。
这条规则的连带影响
1. getClass() 比较运行时类型,getDeclaringClass() 比较枚举类型
1Operation.PLUS.getClass() == Operation.MINUS.getClass(); // false 2Operation.PLUS.getDeclaringClass() == Operation.class; // true 3
JDK 自己的 Enum.compareTo 就是这么写的 ⬇️
1public final int compareTo(E o) { 2 Enum<?> other = o; 3 Enum<E> self = this; 4 if (self.getClass() != other.getClass() && // optimization 5 self.getDeclaringClass() != other.getDeclaringClass()) 6 throw new ClassCastException(); 7 return self.ordinal - other.ordinal; 8} 9
先用 getClass() 做一次快速判断(大多数枚举没有类体,这一步就已经相等),不相等再退回 getDeclaringClass()。
2. 匿名类的元信息是空的
getSimpleName() 返回空串,getCanonicalName() 返回 null,isAnonymousClass() 返回 true。更彻底的一点:OrderStatus$1.isEnum() 是 false、getEnumConstants() 是 null——这个常量的运行时类甚至不算枚举类。判断"它属于哪个枚举"只能靠 getDeclaringClass() 或 ordinal()。
3. 集合类与 switch 不受影响
EnumSet、EnumMap、switch 都基于 ordinal() 或常量本身,实测不受影响 ⬇️
1COMPLETED.compareTo(ON_HOLD) = 1 2EnumMap keys = [ON_HOLD, COMPLETED], size = 2 3EnumSet = [ON_HOLD, COMPLETED] 4
4. 不要依赖 $1 这种命名
Operation$1 ~ $4 的顺序取决于常量的声明顺序和 javac 的实现。JLS §13.1 明确说匿名类的二进制名不可预测,换编译器或调整声明顺序都可能变。
5. 带类体的枚举是隐含 sealed
这一点在样例三里已经看到:isSealed() 为 true,允许的子类就是那些匿名子类。它解释了一个直觉——常量的匿名子类不会被别的代码继承。
完整代码
1import java.awt.BasicStroke; 2import java.awt.BorderLayout; 3import java.awt.Color; 4import java.awt.Component; 5import java.awt.Dimension; 6import java.awt.Font; 7import java.awt.FontMetrics; 8import java.awt.Graphics; 9import java.awt.Graphics2D; 10import java.awt.RenderingHints; 11import java.util.ArrayList; 12import java.util.LinkedHashMap; 13import java.util.List; 14import java.util.Map; 15import java.util.regex.Matcher; 16import java.util.regex.Pattern; 17import javax.swing.BorderFactory; 18import javax.swing.Box; 19import javax.swing.BoxLayout; 20import javax.swing.ButtonGroup; 21import javax.swing.DefaultListModel; 22import javax.swing.JFrame; 23import javax.swing.JLabel; 24import javax.swing.JList; 25import javax.swing.JPanel; 26import javax.swing.JScrollPane; 27import javax.swing.JTable; 28import javax.swing.JTextPane; 29import javax.swing.JToggleButton; 30import javax.swing.ListSelectionModel; 31import javax.swing.SwingUtilities; 32import javax.swing.UIManager; 33import javax.swing.table.DefaultTableCellRenderer; 34import javax.swing.table.DefaultTableModel; 35import javax.swing.text.SimpleAttributeSet; 36import javax.swing.text.StyleConstants; 37import javax.swing.text.StyledDocument; 38 39/** 40 * GUI explorer for the runtime type of enum constants: a constant declared 41 * with a class body is an instance of an anonymous subclass (E$1), so its 42 * getClass() differs from the enum type while getDeclaringClass() does not. 43 * <p> 44 * Note: binary names such as E$1 are NOT part of the spec. JLS 13.1 says the 45 * class file name of an anonymous class is implementation determined, so the 46 * names shown here are whatever the local compiler produced (javac numbers 47 * them in declaration order) and may differ across compilers. 48 * <p> 49 * Run with: 50 * javac EnumTypeGuiDemo.java 51 * java EnumTypeGuiDemo 52 */ 53public class EnumTypeGuiDemo { 54 55 /** Plain enum: every constant is an instance of the enum type itself. */ 56 enum Direction { 57 EAST, WEST, SOUTH, NORTH 58 } 59 60 /** Every constant has a class body, so each one is an anonymous subclass. */ 61 enum Operation { 62 PLUS { 63 double eval(double x, double y) { 64 return x + y; 65 } 66 }, 67 MINUS { 68 double eval(double x, double y) { 69 return x - y; 70 } 71 }, 72 TIMES { 73 double eval(double x, double y) { 74 return x * y; 75 } 76 }, 77 DIVIDED_BY { 78 double eval(double x, double y) { 79 return x / y; 80 } 81 }; 82 83 // Each constant supports an arithmetic operation 84 abstract double eval(double x, double y); 85 } 86 87 /** 88 * A realistic mix: only the terminal states need their own behaviour, and 89 * one constant keeps an empty class body to show that even {@code { }} is 90 * enough to produce a separate subclass. 91 */ 92 enum OrderStatus { 93 CREATED, 94 PAID, 95 SHIPPED, 96 // { } alone still produces a subclass 97 ON_HOLD { }, 98 COMPLETED { 99 @Override 100 boolean isTerminal() { 101 return true; 102 } 103 }, 104 CANCELLED { 105 @Override 106 boolean isTerminal() { 107 return true; 108 } 109 }; 110 111 boolean isTerminal() { 112 return false; 113 } 114 } 115 116 /** One selectable enum type plus the source readers can compare with. */ 117 record Sample(String label, Class<?> type, Enum<?>[] constants, String source) { 118 } 119 120 private static final String DIRECTION_SOURCE = """ 121 enum Direction { 122 EAST, WEST, SOUTH, NORTH 123 } 124 """; 125 126 private static final String OPERATION_SOURCE = """ 127 enum Operation { 128 PLUS { 129 double eval(double x, double y) { return x + y; } 130 }, 131 MINUS { 132 double eval(double x, double y) { return x - y; } 133 }, 134 TIMES { 135 double eval(double x, double y) { return x * y; } 136 }, 137 DIVIDED_BY { 138 double eval(double x, double y) { return x / y; } 139 }; 140 141 abstract double eval(double x, double y); 142 } 143 """; 144 145 private static final String ORDER_STATUS_SOURCE = """ 146 enum OrderStatus { 147 CREATED, 148 PAID, 149 SHIPPED, 150 // { } alone still produces a subclass 151 ON_HOLD { }, 152 COMPLETED { 153 @Override 154 boolean isTerminal() { return true; } 155 }, 156 CANCELLED { 157 @Override 158 boolean isTerminal() { return true; } 159 }; 160 161 boolean isTerminal() { return false; } 162 } 163 """; 164 165 private final List<Sample> samples = List.of( 166 new Sample("Direction (plain)", Direction.class, Direction.values(), DIRECTION_SOURCE), 167 new Sample("Operation (all bodies)", Operation.class, Operation.values(), OPERATION_SOURCE), 168 new Sample("OrderStatus (some bodies)", OrderStatus.class, OrderStatus.values(), 169 ORDER_STATUS_SOURCE)); 170 171 private final HierarchyPanel diagram = new HierarchyPanel(); 172 private final DefaultListModel<String> constantModel = new DefaultListModel<>(); 173 private final JList<String> constantList = new JList<>(constantModel); 174 private final JLabel header = new JLabel(" "); 175 private final DefaultTableModel facts = new DefaultTableModel( 176 new Object[]{"check", "result"}, 0) { 177 @Override 178 public boolean isCellEditable(int row, int column) { 179 return false; 180 } 181 }; 182 private final JTable factTable = new JTable(facts); 183 private final JScrollPane factScroll = new JScrollPane(factTable); 184 private final JTextPane sourcePane = new JTextPane(); 185 private final JScrollPane sourceScroll = new JScrollPane(sourcePane); 186 private final JPanel sourceBox = new JPanel(new BorderLayout()); 187 private final List<JToggleButton> sampleButtons = new ArrayList<>(); 188 189 private Sample current; 190 191 public static void main(String[] args) { 192 SwingUtilities.invokeLater(() -> { 193 useSystemLookAndFeel(); 194 new EnumTypeGuiDemo().show(); 195 }); 196 } 197 198 private static void useSystemLookAndFeel() { 199 try { 200 UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); 201 } catch (Exception ignored) { 202 // keep the default look and feel 203 } 204 } 205 206 private void show() { 207 JFrame frame = new JFrame("enum constant type explorer"); 208 frame.setContentPane(buildPanel()); 209 frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); 210 frame.setSize(1320, 700); 211 frame.setLocationRelativeTo(null); 212 frame.setVisible(true); 213 } 214 215 // ---- layout: left samples + constants, center diagram, right facts ---- 216 217 private JPanel buildPanel() { 218 JPanel left = buildLeftPanel(); 219 JPanel center = buildCenterPanel(); 220 JPanel right = buildRightPanel(); 221 222 JPanel content = new JPanel(new BorderLayout(8, 0)); 223 content.add(left, BorderLayout.WEST); 224 content.add(center, BorderLayout.CENTER); 225 content.add(right, BorderLayout.EAST); 226 227 JPanel panel = new JPanel(new BorderLayout()); 228 panel.setBorder(BorderFactory.createEmptyBorder(8, 8, 8, 8)); 229 panel.setBackground(Color.WHITE); 230 panel.add(content, BorderLayout.CENTER); 231 232 selectSample(samples.get(0)); 233 return panel; 234 } 235 236 private JPanel buildLeftPanel() { 237 JPanel sampleBox = new JPanel(); 238 sampleBox.setLayout(new BoxLayout(sampleBox, BoxLayout.Y_AXIS)); 239 sampleBox.setBorder(BorderFactory.createTitledBorder("sample (enum type)")); 240 sampleBox.setBackground(Color.WHITE); 241 242 ButtonGroup group = new ButtonGroup(); 243 for (Sample sample : samples) { 244 JToggleButton button = new JToggleButton(sample.label()); 245 button.setAlignmentX(Component.LEFT_ALIGNMENT); 246 button.setMaximumSize(new Dimension(Integer.MAX_VALUE, 28)); 247 button.setBackground(Color.WHITE); 248 button.setToolTipText("switch to this enum type"); 249 button.addActionListener(e -> selectSample(sample)); 250 group.add(button); 251 sampleButtons.add(button); 252 sampleBox.add(button); 253 sampleBox.add(Box.createVerticalStrut(4)); 254 } 255 256 constantList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); 257 constantList.setToolTipText("select a constant to inspect its runtime class"); 258 constantList.addListSelectionListener(e -> { 259 if (!e.getValueIsAdjusting()) { 260 updateSelected(); 261 } 262 }); 263 JPanel constantBox = new JPanel(new BorderLayout()); 264 constantBox.setBorder(BorderFactory.createTitledBorder("constants (values())")); 265 constantBox.setBackground(Color.WHITE); 266 constantBox.add(new JScrollPane(constantList), BorderLayout.CENTER); 267 268 JPanel left = new JPanel(new BorderLayout(0, 8)); 269 left.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 8)); 270 left.setBackground(Color.WHITE); 271 left.add(sampleBox, BorderLayout.NORTH); 272 left.add(constantBox, BorderLayout.CENTER); 273 left.setPreferredSize(new Dimension(230, 400)); 274 return left; 275 } 276 277 /** The whole center column belongs to the hierarchy diagram. */ 278 private JPanel buildCenterPanel() { 279 JPanel hierarchy = new JPanel(new BorderLayout(0, 6)); 280 hierarchy.setBackground(Color.WHITE); 281 hierarchy.setBorder(BorderFactory.createTitledBorder( 282 "runtime class hierarchy (computed from getSuperclass())")); 283 hierarchy.add(diagram, BorderLayout.CENTER); 284 285 // legend + compiler note live here as real components (below the 286 // diagram, not painted inside it), so a tall enum can never overlap them 287 JPanel noteStrip = new JPanel(); 288 noteStrip.setLayout(new BoxLayout(noteStrip, BoxLayout.Y_AXIS)); 289 noteStrip.setBackground(Color.WHITE); 290 noteStrip.setBorder(BorderFactory.createMatteBorder(1, 0, 0, 0, new Color(0xe8, 0xdf, 0xcc))); 291 292 JLabel legendLabel = new JLabel("blue border = runtime class of the selected constant"); 293 legendLabel.setFont(legendLabel.getFont().deriveFont(Font.PLAIN, 11f)); 294 legendLabel.setForeground(new Color(0x8c, 0x8c, 0x8c)); 295 legendLabel.setBorder(BorderFactory.createEmptyBorder(5, 10, 2, 10)); 296 legendLabel.setAlignmentX(Component.LEFT_ALIGNMENT); 297 298 // the $1 names come from javac's numbering, not from the spec: JLS 13.1 299 // leaves the class file name of an anonymous class implementation-determined 300 JLabel compilerNote = new JLabel("<html><div style=\"width:560px\">" 301 + "<b>class names like Operation$1 are compiler-specific:</b> shown here is" 302 + " javac's numbering (JLS 13.1 leaves anonymous class names implementation" 303 + " determined); another compiler may name them differently</div></html>"); 304 compilerNote.setFont(compilerNote.getFont().deriveFont(Font.PLAIN, 11f)); 305 compilerNote.setForeground(new Color(0x8a, 0x6d, 0x3b)); 306 compilerNote.setBorder(BorderFactory.createEmptyBorder(2, 10, 5, 10)); 307 compilerNote.setAlignmentX(Component.LEFT_ALIGNMENT); 308 compilerNote.setToolTipText("JLS 13.1: the binary name of an anonymous class" 309 + " is implementation determined"); 310 noteStrip.add(legendLabel); 311 noteStrip.add(compilerNote); 312 hierarchy.add(noteStrip, BorderLayout.SOUTH); 313 return hierarchy; 314 } 315 316 private JPanel buildRightPanel() { 317 factTable.setRowHeight(24); 318 factTable.setShowGrid(true); 319 factTable.setGridColor(new Color(0xee, 0xee, 0xee)); 320 factTable.getColumnModel().getColumn(0).setPreferredWidth(205); 321 factTable.getColumnModel().getColumn(1).setPreferredWidth(265); 322 factTable.setDefaultRenderer(Object.class, new FactRenderer()); 323 324 sourcePane.setEditable(false); 325 sourcePane.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 12)); 326 sourcePane.setBackground(Color.WHITE); 327 sourcePane.setBorder(BorderFactory.createEmptyBorder(4, 8, 4, 8)); 328 sourceBox.setBackground(Color.WHITE); 329 sourceBox.setBorder(BorderFactory.createTitledBorder("enum source")); 330 sourceBox.add(sourceScroll, BorderLayout.CENTER); 331 332 JPanel right = new JPanel(new BorderLayout(0, 6)); 333 right.setBorder(BorderFactory.createEmptyBorder(0, 8, 0, 0)); 334 right.setBackground(Color.WHITE); 335 right.add(header, BorderLayout.NORTH); 336 right.add(factScroll, BorderLayout.CENTER); 337 // SOUTH keeps its preferred height, so the source panel shows its whole 338 // text when the window allows it and never competes with the diagram 339 right.add(sourceBox, BorderLayout.SOUTH); 340 right.setPreferredSize(new Dimension(540, 400)); 341 return right; 342 } 343 344 // ---- data flow ------------------------------------------------------- 345 346 private void selectSample(Sample sample) { 347 current = sample; 348 for (int i = 0; i < sampleButtons.size(); i++) { 349 sampleButtons.get(i).setSelected(samples.get(i) == sample); 350 } 351 constantModel.clear(); 352 for (Enum<?> constant : sample.constants()) { 353 constantModel.addElement(constant.name()); 354 } 355 constantList.setSelectedIndex(0); 356 } 357 358 private void updateSelected() { 359 int index = constantList.getSelectedIndex(); 360 if (current == null || index < 0) { 361 return; 362 } 363 Enum<?> constant = current.constants()[index]; 364 Class<?> type = current.type(); 365 Class<?> runtime = constant.getClass(); 366 Class<?> declaring = constant.getDeclaringClass(); 367 368 int bodies = countBodies(); 369 header.setText(String.format("%s: %d constants, %d with class body, %d class file%s", 370 shortName(type), current.constants().length, bodies, 371 1 + (bodies == 0 ? 0 : childCount()), bodies == 1 ? "" : "s")); 372 373 facts.setRowCount(0); 374 addFact("name()", constant.name()); 375 addFact("getClass().getName()", runtime.getName()); 376 addFact("getClass().getSimpleName()", 377 runtime.getSimpleName().isEmpty() ? "(empty string)" : runtime.getSimpleName()); 378 addFact("getClass().getCanonicalName()", 379 runtime.getCanonicalName() == null ? "null (anonymous class)" : runtime.getCanonicalName()); 380 addFact("getClass().isAnonymousClass()", String.valueOf(runtime.isAnonymousClass())); 381 addFact("getDeclaringClass().getName()", declaring.getName()); 382 addFact("has class body", runtime != type ? "yes" : "no"); 383 addFact("getClass() == E.class", runtime == type ? "✔ true" : "✘ false"); 384 addFact("getDeclaringClass() == E.class", declaring == type ? "✔ true" : "✘ false"); 385 386 diagram.refresh(current, constant); 387 showSource(constant); 388 } 389 390 /** Show the enum source of the current sample, highlighting the constant. */ 391 private void showSource(Enum<?> selected) { 392 String text = current.source(); 393 sourcePane.setText(text); 394 if (selected != null) { 395 StyledDocument doc = sourcePane.getStyledDocument(); 396 SimpleAttributeSet attributes = new SimpleAttributeSet(); 397 StyleConstants.setBold(attributes, true); 398 StyleConstants.setBackground(attributes, new Color(0xe6, 0xf4, 0xff)); 399 Matcher matcher = Pattern.compile("\\b" + Pattern.quote(selected.name()) + "\\b") 400 .matcher(text); 401 while (matcher.find()) { 402 doc.setCharacterAttributes(matcher.start(), 403 matcher.end() - matcher.start(), attributes, false); 404 } 405 } 406 sourcePane.setCaretPosition(0); 407 408 // SOUTH of the right column: follow the content height, the fact table 409 // in CENTER absorbs whatever space is left or scrolls when the window 410 // is short 411 int lineHeight = sourcePane.getFontMetrics(sourcePane.getFont()).getHeight(); 412 int lines = text.split("\n", -1).length; 413 sourceBox.setPreferredSize(new Dimension(0, lines * lineHeight + 8 + 30)); 414 sourceBox.revalidate(); 415 } 416 417 private void addFact(String label, String value) { 418 facts.addRow(new Object[]{label, value}); 419 } 420 421 private int countBodies() { 422 int count = 0; 423 for (Enum<?> constant : current.constants()) { 424 if (constant.getClass() != current.type()) { 425 count++; 426 } 427 } 428 return count; 429 } 430 431 private int childCount() { 432 Map<Class<?>, Boolean> children = new LinkedHashMap<>(); 433 for (Enum<?> constant : current.constants()) { 434 if (constant.getClass() != current.type()) { 435 children.put(constant.getClass(), Boolean.TRUE); 436 } 437 } 438 return children.size(); 439 } 440 441 /** EnumTypeGuiDemo$Operation$1 -> Operation$1 */ 442 private static String shortName(Class<?> type) { 443 String name = type.getName(); 444 int dollar = name.indexOf('$'); 445 return dollar >= 0 ? name.substring(dollar + 1) : name.substring(name.lastIndexOf('.') + 1); 446 } 447 448 private static String joinNames(List<Enum<?>> constants) { 449 List<String> names = new ArrayList<>(); 450 for (Enum<?> constant : constants) { 451 names.add(constant.name()); 452 } 453 return String.join(", ", names); 454 } 455 456 // ---- right panel renderer ------------------------------------------- 457 458 private static final class FactRenderer extends DefaultTableCellRenderer { 459 460 @Override 461 public Component getTableCellRendererComponent(JTable table, Object value, 462 boolean isSelected, boolean hasFocus, int row, int column) { 463 Component component = super.getTableCellRendererComponent( 464 table, value, isSelected, hasFocus, row, column); 465 String text = String.valueOf(value); 466 if (!isSelected) { 467 if (text.startsWith("✔")) { 468 component.setForeground(new Color(0x1a, 0x7f, 0x37)); 469 } else if (text.startsWith("✘")) { 470 component.setForeground(new Color(0xcf, 0x22, 0x2e)); 471 } else if (column == 0) { 472 component.setForeground(new Color(0x59, 0x59, 0x59)); 473 } else { 474 component.setForeground(new Color(0x1f, 0x1f, 0x1f)); 475 } 476 } 477 return component; 478 } 479 } 480 481 // ---- center panel: class hierarchy ---------------------------------- 482 483 private static final class HierarchyPanel extends JPanel { 484 485 private Sample sample; 486 private Enum<?> selected; 487 488 HierarchyPanel() { 489 setBackground(Color.WHITE); 490 } 491 492 void refresh(Sample sample, Enum<?> selected) { 493 this.sample = sample; 494 this.selected = selected; 495 repaint(); 496 } 497 498 @Override 499 protected void paintComponent(Graphics graphics) { 500 super.paintComponent(graphics); 501 Graphics2D g = (Graphics2D) graphics.create(); 502 g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, 503 RenderingHints.VALUE_ANTIALIAS_ON); 504 try { 505 paint(g); 506 } finally { 507 g.dispose(); 508 } 509 } 510 511 private void paint(Graphics2D g) { 512 if (sample == null) { 513 return; 514 } 515 int width = getWidth(); 516 int height = getHeight(); 517 int pad = 18; 518 519 List<Enum<?>> plain = new ArrayList<>(); 520 Map<Class<?>, List<Enum<?>>> children = new LinkedHashMap<>(); 521 for (Enum<?> constant : sample.constants()) { 522 Class<?> runtime = constant.getClass(); 523 if (runtime == sample.type()) { 524 plain.add(constant); 525 } else { 526 children.computeIfAbsent(runtime, key -> new ArrayList<>()).add(constant); 527 } 528 } 529 530 int rootW = 240; 531 int rootH = 66; 532 int rootX = pad; 533 boolean rootSelected = selected != null && selected.getClass() == sample.type(); 534 String rootNote = plain.isEmpty() 535 ? "(every constant has a class body)" 536 : "constants: " + joinNames(plain); 537 538 int count = children.size(); 539 if (count == 0) { 540 int rootY = Math.max(30, (height - rootH) / 2 - 14); 541 drawBox(g, rootX, rootY, rootW, rootH, shortName(sample.type()), 542 "enum type (E.class)", rootNote, rootSelected); 543 g.setColor(new Color(0x1a, 0x7f, 0x37)); 544 g.setFont(new Font("Dialog", Font.PLAIN, 12)); 545 drawCentered(g, "every constant is a plain instance of " 546 + shortName(sample.type()) + " - no subclasses were generated", width, 547 rootY + rootH + 56); 548 return; 549 } 550 551 // root on the left, anonymous subclasses stacked on the right 552 int childX = rootX + rootW + 2 * pad; 553 int childW = Math.max(150, width - childX - pad); 554 int gapY = 10; 555 // shrink the boxes (never below 48px, the 3-line minimum) when the 556 // panel is short, so the block always fits above the note strip 557 int childH = Math.max(48, Math.min(62, 558 (height - 16 - (count - 1) * gapY) / count)); 559 int blockH = count * childH + (count - 1) * gapY; 560 // center the block; never force a 24px top margin when the panel is 561 // too short, or the last box would run into the note strip below 562 int startY = Math.max(8, (height - blockH) / 2); 563 int rootY = startY + blockH / 2 - rootH / 2; 564 565 drawBox(g, rootX, rootY, rootW, rootH, shortName(sample.type()), 566 "enum type (E.class)", rootNote, rootSelected); 567 568 int rootCy = rootY + rootH / 2; 569 int i = 0; 570 for (Map.Entry<Class<?>, List<Enum<?>>> entry : children.entrySet()) { 571 Class<?> runtime = entry.getKey(); 572 int cy = startY + i * (childH + gapY) + childH / 2; 573 574 g.setColor(new Color(0xbf, 0xbf, 0xbf)); 575 g.setStroke(new BasicStroke(1f)); 576 g.drawLine(rootX + rootW, rootCy, childX, cy); 577 g.drawLine(childX - 7, cy - 4, childX, cy); 578 g.drawLine(childX - 7, cy + 4, childX, cy); 579 580 boolean highlighted = selected != null && selected.getClass() == runtime; 581 drawBox(g, childX, cy - childH / 2, childW, childH, 582 shortName(runtime), 583 runtime.isAnonymousClass() ? "anonymous subclass" : "subclass", 584 "constants: " + joinNames(entry.getValue()), highlighted); 585 i++; 586 } 587 } 588 589 private void drawCentered(Graphics2D g, String text, int width, int y) { 590 FontMetrics metrics = g.getFontMetrics(); 591 g.drawString(text, (width - metrics.stringWidth(text)) / 2, y); 592 } 593 594 private void drawBox(Graphics2D g, int x, int y, int w, int h, 595 String title, String subtitle, String constants, boolean highlighted) { 596 g.setColor(highlighted ? new Color(0xe6, 0xf4, 0xff) : Color.WHITE); 597 g.fillRoundRect(x, y, w, h, 8, 8); 598 g.setColor(highlighted ? new Color(0x16, 0x77, 0xff) : new Color(0xbf, 0xbf, 0xbf)); 599 g.setStroke(new BasicStroke(highlighted ? 2f : 1f)); 600 g.drawRoundRect(x, y, w, h, 8, 8); 601 g.setStroke(new BasicStroke(1f)); 602 603 // text baselines scale with the box height (the layout was designed 604 // for h = 62), so a shrunken box keeps all three lines inside 605 g.setColor(new Color(0x1f, 0x1f, 0x1f)); 606 g.setFont(new Font("Dialog", Font.BOLD, 13)); 607 g.drawString(clip(g, title, w - 20), x + 10, y + h * 21 / 62); 608 609 g.setColor(new Color(0x59, 0x59, 0x59)); 610 g.setFont(new Font("Dialog", Font.PLAIN, 11)); 611 g.drawString(clip(g, subtitle, w - 20), x + 10, y + h * 40 / 62); 612 g.drawString(clip(g, constants, w - 20), x + 10, y + h * 58 / 62); 613 } 614 615 private String clip(Graphics2D g, String text, int maxWidth) { 616 FontMetrics metrics = g.getFontMetrics(); 617 if (metrics.stringWidth(text) <= maxWidth) { 618 return text; 619 } 620 String ellipsis = "..."; 621 int end = text.length(); 622 while (end > 0 && metrics.stringWidth(text.substring(0, end) + ellipsis) > maxWidth) { 623 end--; 624 } 625 return text.substring(0, end) + ellipsis; 626 } 627 } 628} 629 630
参考文档
- Primers 编程伙伴/HTML/HTML 元素/main
- Primers 编程伙伴/Bash/帮助手册/eval
- Primers 编程伙伴/Bash/帮助手册/type
- Primers 编程伙伴/Bash/帮助手册/source
- Primers 编程伙伴/Bash/帮助手册/false
- Primers 编程伙伴/HTML/HTML 元素/p
- Primers 编程伙伴/Bash/帮助手册/true
- Primers 编程伙伴/HTML/HTML 元素/body
- Primers 编程伙伴/Bash/帮助手册/yes
《为什么枚举类中可以定义抽象方法》 是转载文章,点击查看原文。