遍历
枚举类:
public enum Color{
RED("红色"),GREEN("绿色",1),BLACK("黑色",2);
private String name;
private Integer index;
//构造函数
private Color(String name, Integer index){
this.name = name;
this.index = index;
}
//构造函数
private Color(String name){
this.name = name;
}
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
public Integer getIndex(){
return index;
}
public void setIndex(Integer index){
this.index = index;
}
}
测试类
public class TestColor{
public static void main(String[] args){
System.out.println(Color.BLACK.getName());//黑色
System.out.println(Color.BLACK.getIndex());//2
System.out.println(Color.valueOf("RED"));//RED
//遍历枚举的值
for(Color color:Color.values()){
System.out.println( color + "name:" + color.getName() + "index:" + color.getIndex() );
/* REDname:红色index:null
GREENname:绿色index:1
BLACKname:黑色index:2*/
}
}
}
反射获取值
枚举类:
public enum Color{
RED,GREEN,BLACK;
}
测试类:
public class TestColor{
public static void main(String[] args){
Class cla = Color.class;
System.out.println(cla.isEnum());//true
Object object = null;
Object[] objArray = cla.getEnumConstants();
for(Object obj:objArray){
System.out.println(obj.toString());//RED GREEN BLACK
if(obj.toString().equals("RED")){
object = obj;
}
}
System.out.println(object.toString());//RED
}
}
网友评论