V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
hello2060
V2EX  ›  Java

问个简单的问题

  •  
  •   hello2060 · Apr 20, 2021 · 2120 views
    This topic created in 1834 days ago, the information mentioned may be changed or developed.

    一个类里面定义了很多常量

    public class Codes {
    
        static final public ErrorCode ISSUE_1 = new ErrorCode(XXX);  
        static final public ErrorCode ISSUE_2 = new ErrorCode(XXX);
        
        // 一共上百个定义 
    }
    

    现在要一个 Codes.getAll() 返回所有定义的 ErrorCode 。

    请问有啥好点的方法吗?

    jjwjiang
        1
    jjwjiang  
       Apr 20, 2021
    这不典型的反射场景吗
    Littlerain
        2
    Littlerain  
       Apr 20, 2021
    ```java
    static List<ErrorCode> errorCodes;
    static {
    errorCodes = = new ArrayList<>();
    for(Field f : Codes.class.getDeclaredFields()) {
    if (f.getType() == ErrorCode.class) {
    ErrorCodes.add(f.get(new ErrorCode()))
    }
    }
    }
    ```
    hhyyd
        3
    hhyyd  
       Apr 20, 2021 via Android
    常量完全可以存 enum,然后 getValues()
    hhyyd
        4
    hhyyd  
       Apr 20, 2021 via Android
    @hhyyd 哦,不是 get,直接.values()
    hello2060
        5
    hello2060  
    OP
       Apr 20, 2021 via iPhone
    谢谢各位,确实可以用反射,谢谢啦
    hello2060
        6
    hello2060  
    OP
       Apr 20, 2021 via iPhone
    @hhyyd enum 应该也可以
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5641 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 49ms · UTC 08:30 · PVG 16:30 · LAX 01:30 · JFK 04:30
    ♥ Do have faith in what you're doing.