接口中的静态初始化 [英] static initialization in interface

查看:134
本文介绍了接口中的静态初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试写这样的东西时:

When I tried to write something like this:

public interface MyInterface {
    static {
        System.out.println("Hello!");
    }
}

编译器无法编译它。

但是当我写这样的东西时:

But when I wrote something like this:

interface MyInterface {
    Integer iconst = Integer.valueOf(1);
}

并反编译它,我看到静态初始化:

and decompiled it, I saw static initialization:

public interface MyInterface{
    public static final java.lang.Integer i;

    static {};
      Code:
      0:   iconst_1
      1:   invokestatic    #1; //Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
      4:   putstatic       #2; //Field i:Ljava/lang/Integer;
      7:   return
}

您可以向我解释一下这种行为吗?

Could you please explain this behavior to me?

推荐答案

您可以进行静态初始化,但不能使用静态块。静态初始化需要实现静态代码块的事实确实改变了Java语法。

You can have static initialisation, but you cannot have a static block. The fact the static initialisation needs a static code block to implement does change the Java syntax.

关键是你不打算在接口中使用代码(在Java 8之前)但是你可以初始化字段。

The point is you are not meant to have code in an interface (before Java 8) but you are allowed to initialise fields.

BTW你可以拥有一个嵌套的类或枚举,它拥有你喜欢的代码,你可以在初始化字段时调用它。 ;)

BTW you can have a nested class or enum which has as much code as you like and you can call this while initialising a field. ;)

这篇关于接口中的静态初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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