Skip to content

Commit

Permalink
Add getEnumConstants() method
Browse files Browse the repository at this point in the history
  • Loading branch information
lukehutch committed Dec 6, 2021
1 parent 52db73f commit ce52201
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 0 deletions.
14 changes: 14 additions & 0 deletions src/main/java/io/github/classgraph/ClassInfo.java
Expand Up @@ -51,6 +51,7 @@

import io.github.classgraph.Classfile.ClassContainment;
import io.github.classgraph.Classfile.ClassTypeAnnotationDecorator;
import io.github.classgraph.FieldInfoList.FieldInfoFilter;
import nonapi.io.github.classgraph.json.Id;
import nonapi.io.github.classgraph.scanspec.ScanSpec;
import nonapi.io.github.classgraph.types.ParseException;
Expand Down Expand Up @@ -2666,6 +2667,19 @@ public FieldInfoList getFieldInfo() {
return fieldInfoList;
}

/** Get all enum constants of an enum class (as a list of {@link FieldInfo} objects). */
public FieldInfoList getEnumConstants() {
if (!isEnum()) {
throw new IllegalArgumentException("Class " + getName() + " is not an enum");
}
return getFieldInfo().filter(new FieldInfoFilter() {
@Override
public boolean accept(FieldInfo fieldInfo) {
return fieldInfo.isEnum();
}
})
}

/**
* Returns information on the named field declared by the class, but not by its superclasses. See also:
*
Expand Down
39 changes: 39 additions & 0 deletions src/test/java/io/github/classgraph/features/EnumTest.java
@@ -0,0 +1,39 @@
package io.github.classgraph.features;

import static org.assertj.core.api.Assertions.assertThat;

import org.junit.jupiter.api.Test;

import io.github.classgraph.ClassGraph;
import io.github.classgraph.ClassInfo;
import io.github.classgraph.FieldInfo;
import io.github.classgraph.ScanResult;

/**
* Test.
*/
public class EnumTest {
/** Enum */
private static enum MyEnum {
A, B, C;
}

/**
* Test records (JDK 14+).
*
* @throws Exception
* the exception
*/
@Test
public void recordJar() throws Exception {
try (ScanResult scanResult = new ClassGraph().acceptClasses(MyEnum.class.getName()).enableAllInfo()
.scan()) {
assertThat(scanResult.getAllEnums().size() == 1);
final ClassInfo myEnum = scanResult.getAllEnums().get(0);
assertThat(myEnum.getName().equals(MyEnum.class.getName()));
for (FieldInfo fi : myEnum.getFieldInfo()) {
System.out.println(fi);
}
}
}
}

0 comments on commit ce52201

Please sign in to comment.