什么时候执行这些类和子类的静态块(对于枚举)? [英] When are these class and subclass static blocks executed (for an Enum)?

查看:144
本文介绍了什么时候执行这些类和子类的静态块(对于枚举)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为枚举定义一个基类( SubStatus )。

I'm trying to define a base class (SubStatus) for an Enum.

什么时候 static 块下面调用块如果他们是类而不是枚举,我相信他们会在类构造函数被调用后被调用?

When are the static blocks called below? If they were classes rather than enums I believe they would be called after the class constructor is called?

但是因为它们是枚举 s,这些不是更像 static 类开始吗?所以也许在容器加载静态实例时执行静态块?

But because they are Enums, aren't these more like static classes to begin with? So perhaps the static blocks are execute when the container is loading the static instances?

public enum SubStatus
{
     WAITING(0),
     READY(1);

     protected static final Map<Integer,SubStatus> lookup 
          = new HashMap<Integer,SubStatus>();

     static {
          for(SubStatus s : EnumSet.allOf(SubStatus.class))
               lookup.put(s.getCode(), s);
     }

     protected int code;

     protected SubStatus(int code) {
          this.code = code;
     }

     public int getCode() { return code; }

     public static SubStatus get(int code) { 
          return lookup.get(code); 
     }
}



状态



Status

public enum Status extends SubStatus
{
     SKIPPED(-1),
     COMPLETED(5);

     private static final Map<Integer,Status> lookup 
          = new HashMap<Integer,Status>();

     static {
          for(Status s : EnumSet.allOf(Status.class))
               lookup.put(s.getCode(), s);
     }

     private int code;

     private Status(int code) {
          this.code = code;
     }

     public int getCode() { return code; }

     public static Status get(int code) { 
          return lookup.get(code); 
     }
}


推荐答案

当第一次调用enum时,静态块被处理,但在所有枚举值被创建之后。 Btw,你的代码不行。 Java枚举中没有继承。如果您需要这样的话,可以到达接口。

The static block is processed when the first call to you enum has been made but after all enums values have been created. Btw, your code won't work. There is no inheritance in Java enums. Resort to interfaces if you need something like this.

这篇关于什么时候执行这些类和子类的静态块(对于枚举)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆