Wednesday, October 22, 2025
HomeLanguagesJavaClass getEnumConstants() method in Java with Examples

Class getEnumConstants() method in Java with Examples

The getEnumConstants() method of java.lang.Class class is used to get the Enum constants of this class. The method returns the Enum constants of this class in the form of an array of objects comprising the enum class represented by this class.

Syntax:

public T[] getEnumConstants()

Parameter: This method does not accepts any parameter

Return Value: This method returns the specified Enum constants of this class in the form of an array of Enum objects.

Below programs demonstrate the getEnumConstants() method.

Example 1:




// Java program to demonstrate
// getEnumConstants() method
  
import java.util.*;
  
enum A {}
  
public class Test {
  
    public Object obj;
  
    public static void main(String[] args)
    {
  
        // returns the Class object for this class
        Class myClass = A.class;
  
        System.out.println("Class represented by myClass: "
                           + myClass.toString());
  
        // Get the Enum constants of myClass
        // using getEnumConstants() method
        System.out.println(
            "Enum constants of myClass: "
            + Arrays.toString(
                  myClass.getEnumConstants()));
    }
}


Output:

Class represented by myClass: class A
Enum constants of myClass: []

Example 2:




// Java program to demonstrate
// getEnumConstants() method
  
import java.util.*;
  
enum A {
    RED,
    GREEN,
    BLUE;
}
  
class Main {
  
    private Object obj;
  
    public static void main(String[] args)
    {
  
        try {
  
            // returns the Class object for this class
            Class myClass = A.class;
  
            System.out.println("Class represented by myClass: "
                               + myClass.toString());
  
            // Get the Enum constants of myClass
            // using getEnumConstants() method
            System.out.println(
                "Enum constants of myClass: "
                + Arrays.toString(
                      myClass.getEnumConstants()));
        }
        catch (Exception e) {
            System.out.println(e);
        }
    }
}


Output:

Class represented by myClass: class A
Enum constants of myClass: [RED, GREEN, BLUE]

Reference: https://docs.oracle.com/javase/9/docs/api/java/lang/Class.html#getEnumConstants–

Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Dominic
32361 POSTS0 COMMENTS
Milvus
88 POSTS0 COMMENTS
Nango Kala
6728 POSTS0 COMMENTS
Nicole Veronica
11892 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11954 POSTS0 COMMENTS
Shaida Kate Naidoo
6852 POSTS0 COMMENTS
Ted Musemwa
7113 POSTS0 COMMENTS
Thapelo Manthata
6805 POSTS0 COMMENTS
Umr Jansen
6801 POSTS0 COMMENTS