Home » Java programming language

Java Class class getEnumConstants() method with example

Class class getEnumConstants() method: Here, we are going to learn about the getEnumConstants() method of Class class with its syntax and example.
Submitted by Preeti Jain, on November 22, 2019

Class class getEnumConstants() method

  • getEnumConstants() method is available in java.lang package.
  • getEnumConstants() method is used to return an array of enum constants or in other words, we can say this method is used to returns the elements of this enum class.
  • getEnumConstants() method is a non-static method, it is accessible with the class object only and if we try to access the method with the class name then we will get an error.
  • getEnumConstants() method does not throw an exception at the time of returning an enum constant.

Syntax:

    public T[] getEnumConstants();

Parameter(s):

  • It does not accept any parameter.

Return value:

The return type of this method is T[], it returns the following value based on the given case,

  • It returns an array of enum constants in the same order as they were declared when this object denotes an enum type.
  • It returns null when this class object does not represent an enum type.

Example:

// Java program to demonstrate the example 
// of T[]  getEnumConstants () method of Class 

// Enum Definition
enum Fruits {
 Apple,
 Orange,
 Banana,
 Grapes,
}
public class GetEnumConstantsOfClass {
 public static void main(String[] args) {

  // Get class
  Class cl = Fruits.class;

  // Copying enum constants one by one in Object
  for (Object o: cl.getEnumConstants())
   System.out.println(o);
 }
}

Output

Apple
Orange
Banana
Grapes


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.