logo

Metoda Java Enum valueOf().

Metoda valueOf() klase Enum vraća konstantu enum (definiranog tipa enum) zajedno s definiranim imenom.

Sintaksa

 public static <t extends enum> T valueOf(Class enumType,String name) </t>

Parametri tipa:

T : To je enum tip čija se konstanta daje.

np.nule

Parametri

enumType - To je objekt klase tipa enum koji vraća konstantu

Ime - To je ime konstante koju treba vratiti

Povratna vrijednost

Metoda valueOf() vraća enum konstantu zajedno s definiranim imenom.

Bacanja

Metoda valueOf() izbacuje:

  1. IllegalArgumentException, ako definirani tip enuma nije konstantan s definiranim imenom ili tip enuma nije ilustriran definiranim objektom klase.
  2. NullPointerException, ako enumType ili name predstavljaju null vrijednost.

Primjer 1

 enum Parts{ Skin, Muscles,Bones,Organs,Tissue; } public class Enum_valueOfMethodExample1 { public static void main(String[] args) { System.out.println(&apos;The part which is exposed to the environment is :&apos;); for(Parts part : Parts.values()){ int i = part.ordinal()+1; System.out.println(i+&apos; &apos;+part); } Parts part = Parts.valueOf(&apos;Skin&apos;); System.out.println(&apos;
Ans: &apos;+part); } } 
Testirajte sada

Izlaz:

 The part which is exposed to the environment is : 1 Skin 2 Muscles 3 Bones 4 Organs 5 Tissue Ans: Skin 

Primjer 2

 enum Flower{ Rose,Lily, Orchids, Sunflower,Jasmine; } public class Enum_valueOfMethodExample2 { public static void main(String[] args) { System.out.println(&apos;The part which is exposed to the environment is :&apos;); for(Flower flower : Flower.values()) { System.out.println(Flower.valueOf(&apos; &apos;)); } } } 
Testirajte sada

Izlaz:

pyspark sql
 Exception in thread &apos;main&apos; java.lang.IllegalArgumentException: No enum constant com.javaTpoint.Flower. The part which is exposed to the environment is : atjava.lang.Enum.valueOf(Enum.java:238) atcom.javaTpoint.Flower.valueOf(Enum_valueOfMethodExample2.java:4) at com.javaTpoint.Enum_valueOfMethodExample2.main(Enum_valueOfMethodExample2.java:11)