Skip to content

Commit ce52201

Browse files
committed
Add getEnumConstants() method
1 parent 52db73f commit ce52201

2 files changed

Lines changed: 53 additions & 0 deletions

File tree

src/main/java/io/github/classgraph/ClassInfo.java

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,7 @@
5151

5252
import io.github.classgraph.Classfile.ClassContainment;
5353
import io.github.classgraph.Classfile.ClassTypeAnnotationDecorator;
54+
import io.github.classgraph.FieldInfoList.FieldInfoFilter;
5455
import nonapi.io.github.classgraph.json.Id;
5556
import nonapi.io.github.classgraph.scanspec.ScanSpec;
5657
import nonapi.io.github.classgraph.types.ParseException;
@@ -2666,6 +2667,19 @@ public FieldInfoList getFieldInfo() {
26662667
return fieldInfoList;
26672668
}
26682669

2670+
/** Get all enum constants of an enum class (as a list of {@link FieldInfo} objects). */
2671+
public FieldInfoList getEnumConstants() {
2672+
if (!isEnum()) {
2673+
throw new IllegalArgumentException("Class " + getName() + " is not an enum");
2674+
}
2675+
return getFieldInfo().filter(new FieldInfoFilter() {
2676+
@Override
2677+
public boolean accept(FieldInfo fieldInfo) {
2678+
return fieldInfo.isEnum();
2679+
}
2680+
})
2681+
}
2682+
26692683
/**
26702684
* Returns information on the named field declared by the class, but not by its superclasses. See also:
26712685
*
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
package io.github.classgraph.features;
2+
3+
import static org.assertj.core.api.Assertions.assertThat;
4+
5+
import org.junit.jupiter.api.Test;
6+
7+
import io.github.classgraph.ClassGraph;
8+
import io.github.classgraph.ClassInfo;
9+
import io.github.classgraph.FieldInfo;
10+
import io.github.classgraph.ScanResult;
11+
12+
/**
13+
* Test.
14+
*/
15+
public class EnumTest {
16+
/** Enum */
17+
private static enum MyEnum {
18+
A, B, C;
19+
}
20+
21+
/**
22+
* Test records (JDK 14+).
23+
*
24+
* @throws Exception
25+
* the exception
26+
*/
27+
@Test
28+
public void recordJar() throws Exception {
29+
try (ScanResult scanResult = new ClassGraph().acceptClasses(MyEnum.class.getName()).enableAllInfo()
30+
.scan()) {
31+
assertThat(scanResult.getAllEnums().size() == 1);
32+
final ClassInfo myEnum = scanResult.getAllEnums().get(0);
33+
assertThat(myEnum.getName().equals(MyEnum.class.getName()));
34+
for (FieldInfo fi : myEnum.getFieldInfo()) {
35+
System.out.println(fi);
36+
}
37+
}
38+
}
39+
}

0 commit comments

Comments
 (0)