简体   繁体   English

内部类的静态初始化程序?

[英]Static initializer on a inner class?

How to allow static initializer on a inner class like this: 如何在内部类上允许静态初始化程序,如下所示:

public class MyClass {

    public class InnerClass {
        static {
            // do something
        }
        public bar(){
            // do something
        }
    }

    // method stuff
    public void foo() {
        // do something
    }

} 

From JLS 8.1.3 Inner Classes and Enclosing Instances : JLS 8.1.3内部类和封闭实例

Inner classes may not declare static initializers (§8.7) or member interfaces. 内部类可能不会声明静态初始化器(第8.7节)或成员接口。

What you may want is a nested class: 你可能想要的是一个嵌套类:

public static class InnerClass { // note "static"

You need to define the InnerClass class as static. 您需要将InnerClass类定义为static。 But, thereafter, it won't be a regular inner class. 但是,此后,它不会成为常规的内部阶级。

As it's already stated by @yshavit you can't declare static initializers, but from what I found you can get around that by declaring a method to do any initializations you want and simply call it when defining your class' fields. 正如@yshavit已经说过的那样,你不能声明静态初始化器,但是从我发现你可以通过声明一个方法来进行你想要的任何初始化并在定义类的字段时简单地调用它。 For example I implemented this iterator (this is an anonymous inner class) : 例如,我实现了这个迭代器(这是一个匿名的内部类):

public Iterator<String> iterator() {

    return new Iterator<String>() {

        int someField = initializeIterator();

        // Keeps current position in the list of direct neighboring out

        private int initializeIterator() {
            // Do your initializations 
        }

        @Override
        public boolean hasNext() {
            //hasNext implementation
        }

        @Override
        public Vertex next() { 
            //next implementation
         } 
         //...

This feels very hack-y and I wonder If I'm missing something but this totally works and the initialization method is only called once just like a static initialization block would be... 这感觉非常黑客,我想知道如果我错过了什么,但这完全有效,初始化方法只调用一次,就像静态初始化块一样......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM