Java笔记-通过反射获取枚举类型中所有数据

x33g5p2x  于2021-11-10 转载在 Java  
字(1.0k)|赞(0)|评价(0)|浏览(507)

程序运行截图如下:

代码如下:

Em.java

package cn.it1995;

public enum Em {

    ONE(1, "第一个枚举"),
    TWO(2, "第二个枚举"),
    THREE(3, "第三个枚举"),
    FOUR(4, "第四个枚举");

    private Integer id;
    private String describe;

    Em(Integer id, String describe){

        this.id = id;
        this.describe = describe;
    }

    public Integer getId() {

        return id;
    }

    public String getDescribe() {

        return describe;
    }
}

Main.java

package cn.it1995;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class Main {

    public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {

        Class<Em> emClass = Em.class;
        //Em[] enumConstants = emClass.getEnumConstants();
        Object[] objects = emClass.getEnumConstants();
        Method getId = emClass.getMethod("getId");
        Method getDescribe = emClass.getMethod("getDescribe");

        for(Object object : objects){

            System.out.println("id:" + Integer.valueOf(getId.invoke(object).toString()) + "->describe:" + getDescribe.invoke(object).toString());
        }
    }
}

相关文章