Stopping repetition in Java enums

后端 未结 4 1549
梦谈多话
梦谈多话 2020-12-03 16:26

I have the following enum in a Java class:

public enum Resolution {
    RES_32 (32),
    RES_64 (64);
    private final int asInt;
    private R         


        
4条回答
  •  自闭症患者
    2020-12-03 16:53

    The following lets you work with enums on runtime, this is the reference link http://www.theserverside.com/news/thread.tss?thread_id=50190:

    Constructor con = Day.class.getDeclaredConstructors()[0]; 
    Method[] methods = con.getClass().getDeclaredMethods(); 
    for (Method m : methods) 
    { 
        if (m.getName().equals("acquireConstructorAccessor")) 
        { 
            m.setAccessible(true); 
            m.invoke(con, new Object[0]); 
        } 
    }
    
    Field[] fields = con.getClass().getDeclaredFields(); 
    Object ca = null; 
    for (Field f : fields) 
    { 
        if (f.getName().equals("constructorAccessor")) 
        { 
            f.setAccessible(true); 
            ca = f.get(con); 
        } 
    }
    
    Method m = ca.getClass().getMethod( "newInstance", new Class[] { Object[].class }); 
    m.setAccessible(true); 
    Day v = (Day) m.invoke(ca, new Object[] { new Object[] { "VACATION", Integer.MAX_VALUE } }); 
    System.out.println(v.getClass() + ":" + v.name() + ":" + v.ordinal());
    

提交回复
热议问题