File: GetClassOnEnum.md

package info (click to toggle)
error-prone-java 2.18.0-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 23,204 kB
  • sloc: java: 222,992; xml: 1,319; sh: 25; makefile: 7
file content (45 lines) | stat: -rw-r--r-- 871 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
Enum values that declare methods are a subclass of the actual enum type, so
calling `getClass()` returns a synthetic subclass of the enum. To retrieve the
type of the enum, use `getDeclaringClass()`.

In the following example, `Binop.MULT.getClass()` returns the anonymous class
`Binop$2`, while `Binop.MULT.getDeclaringClass()` returns the class `Binop`.

```java
enum Binop {
  MULT {
    @Override
    int apply(int x) {
      return x * x;
    }
  },
  ADD {
    @Override
    int apply(int x) {
      return x + x;
    }
  };

  abstract int apply(int x);
}
```

```java
public class Test {
  static void printEnumClass(Enum theEnum) {
    System.err.println(theEnum.getClass());
    System.err.println(theEnum.getDeclaringClass());
  }

  public static void main(String[] args) {
    printEnumClass(Binop.ADD);
  }
}
```

Prints:

```
class Binop$2
class Binop
```