代码之家  ›  专栏  ›  技术社区  ›  Alexander Mills

静态块中不允许使用公共修饰符?

  •  0
  • Alexander Mills  · 技术社区  · 7 年前

    我有这个:

    public class Models {
    
      public static class User extends BaseModel {
    
    
        public static {
    
          public final TableField ID = new TableField("user_id", "userId");
    
          public final TableField HANDLE = new TableField("user_handle", "userHandle");
    
          public final TableField EMAIL = new TableField("user_email", "userEmail");
    
        }
    
      }
    
    }
    

    java说,在“publicstatic{}”块中的static之前或final之前,不允许public作为修饰符。有人知道为什么吗?也许我不明白静态块与将所有3个字段声明为 public final static .

    这就是我所看到的:

    enter image description here

    还有这个

    enter image description here

    2 回复  |  直到 7 年前
        1
  •  5
  •   khachik    7 年前

    public ,作为访问修饰符,不能应用于代码块,也不能应用于代码块内的局部变量。

    似乎您只想声明静态最终字段:

    ...
    public static final TableField ID = new TableField("user_id", "userId");
    ...
    

    不需要使用 static

        2
  •  3
  •   flakes    7 年前

    initializer blocks ,或在本例中为 static initializer block . 对于前者,可以将视为在初始化期间运行的构造函数代码的扩展。在后一种情况下,它们在类的静态初始化期间(即第一次访问类时)运行。

    这些块对于设置可能需要多行执行的字段或设置外部资源非常有用。

    public class Foobar {
        final static int FOO;
        // runs when first loading Foobar.class
        static {
            int i = 1;
            i += 2;
            FOO = i;
        }
        final int bar;
        // runs when first initializing new Foobar()
        {
            int j = 3;
            j += 4;
            bar = i;
        }
    }
    

    一般来说,它们不是很常见,但它们特别有用的一点是用于绑定本机JNI库。例如,此方法可确保 foobar.dll 在访问类之前加载。

    public class FoobarJNI {
        static {
            System.loadLibrary("foobar"); 
        }
    
        private native void foo();
        private native void bar();
    }