简体   繁体   English

Java中未命名代码块的目的是什么?

[英]What is the purpose of unnamed code blocks in Java?

In my Java class, I have statements in {} without any names/references associated with it and it appear to get executed before constructor is run. 在我的Java类中,我在{}没有与之关联的名称/引用的语句,并且它似乎在构造函数运行之前已被执行。 What is the purpose of it? 目的是什么? Is it possible to call it like calling a method by associating a variable/reference to it? 是否可以像通过关联变量/引用来调用方法那样来调用它? If not, can I change the order in which it is triggered? 如果没有,我可以更改触发顺序吗?

package com.core.java;

public class App {

    public static void main(String[] args) {
        new App();
    }

    static { System.out.print("static block, "); }      
    App() { System.out.print("constructor, "); }    
    { System.out.print("what_is_this? "); }

}

I have seen similar construct in Ruby where it can be associated with a reference and be called at will. 我在Ruby中看到过类似的构造,可以将其与引用关联并随意调用。 For instance 例如

v = -> { puts "A Code Block" }
v.call #=> prints -> A Code Block

If you want to have a quick read on these constructs and what they may be used for, see 如果您想快速阅读这些结构及其用途,请参阅

http://docs.oracle.com/javase/tutorial/java/javaOO/initial.html http://docs.oracle.com/javase/tutorial/java/javaOO/initial.html

The comparison to Ruby is somewhat flawed, as this is only a syntactic similarity between Java and Ruby - in Ruby, the "{}" means something completely different to what Java uses this syntax for. 与Ruby的比较有些瑕疵,因为这只是Java和Ruby之间的语法相似性-在Ruby中,“ {}”的含义与Java使用此语法的含义完全不同。 The "-> {}" in Ruby is an expression returning a lambda, which is a callable object. Ruby中的“-> {}”是一个返回lambda的表达式,它是一个可调用的对象。

What is an initialization block? 什么是初始化块?

Also helps explaining the case with some nice code examples. 还可以通过一些不错的代码示例来帮助解释这种情况。

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

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