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:
- IllegalArgumentException, če definirani tip enum ni konstanten z definiranim imenom ali če definirani objekt razreda ne ponazarja tipa enum.
- 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('The part which is exposed to the environment is :'); for(Parts part : Parts.values()){ int i = part.ordinal()+1; System.out.println(i+' '+part); } Parts part = Parts.valueOf('Skin'); System.out.println(' Ans: '+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('The part which is exposed to the environment is :'); for(Flower flower : Flower.values()) { System.out.println(Flower.valueOf(' ')); } } }Preizkusite zdaj
Izhod:
Exception in thread 'main' 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)