logo

Metoda Java Enum valueOf().

Metoda valueOf() razreda Enum vrne konstanto enum (definirane vrste enum) skupaj z definiranim imenom.

Sintaksa

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

Parametri tipa:

T : To je tip enum, katerega konstanta je pridobljena.

Parametri

enumType - To je objekt razreda enum tipa, ki vrne konstanto

java indexof

ime - To je ime konstante, ki jo je treba vrniti

Povratna vrednost

Metoda valueOf() vrne konstanto enum skupaj z definiranim imenom.

Meti

Metoda valueOf() vrže:

  1. IllegalArgumentException, če definirani tip enum ni konstanten z definiranim imenom ali če definirani objekt razreda ne ponazarja tipa enum.
  2. NullPointerException, če enumType ali name predstavlja ničelno vrednost.

Primer 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); } } 
Preizkusite zdaj

Izhod:

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

Primer 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;)); } } } 
Preizkusite zdaj

Izhod:

 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)