简体   繁体   English

java只是花括号

[英]java just curly braces

I was reading a book and there were a few example with programs that has just curly braces我正在读一本书,有一些程序示例只有花括号

for example例如

 public static void main(String args[]){
     //what is the uses of curly braces here.
     {
          //some code
     }
 }

It's a code block.这是一个代码块。 The variables declared in there are not visible in the upper block (method body outside of these curlies), ie they have a more limited scope.在那里声明的变量在上块(这些卷曲之外的方法体)中是不可见的,即它们的范围更有限。

Be careful, it is NOT ALWAYS an initialisation block as others have suggested.小心,它并不总是像其他人建议的那样是一个初始化块。 In your case it is a variable scoping mechanism called a Code Block or block.在您的情况下,它是一种称为代码块或块的可变范围机制。

If it is outside of a method, then it is!如果它在方法之外,那么它就是!

Example示例

public class MyClass {

   {
      // this is an initialisation block
   }

}

However, if it is inside a method, it is NOT!但是,如果它在方法内部,则不是! In this case (which is the case in your example), it is a code block.在这种情况下(在您的示例中就是这种情况),它是一个代码块。 Anything initialised inside the curly braces is not visible outside在花括号内初始化的任何东西在外面都是不可见的

Example示例

public static void main(String args[]){

     {
          String myString = "you can't see me!";
     }
     System.out.println(myString); // this will not compile because myString is not visible.
 }

This idea of how to use curly braces as a coding construct is a debated issue in the Java world .如何使用花括号作为编码结构的想法在 Java 世界中是一个有争议的问题。 There are several explanations people come up with when they see curly braces by themselves.人们在自己看到花括号时会想到几种解释。 So Im going to try to answer your question from a practical perspective.所以我会尝试从实际的角度来回答你的问题。

The implied question in your post here is, really - when/why are these used ?您在这里的帖子中隐含的问题是,真的 - 何时/为什么使用这些? Practically speaking, the following cases might result in a lone code block :实际上,以下情况可能会导致一个单独的代码块:

1) The programmer wanted additionally scoping to reuse variable names without fear of collisions for clarity (ie making several objects of the same type in a unit test or database insertion block). 1) 为了清楚起见,程序员想要额外的作用域来重用变量名而不必担心冲突(即在单元测试或数据库插入块中创建多个相同类型的对象)。

other possible reasons :其他可能的原因:

2) Forgotten if/else/for/while loop code that is under development. 2) 忘记了正在开发的 if/else/for/while 循环代码。

3) Remaining artifact of a removed if/else/for/while clause. 3) 删除的 if/else/for/while 子句的剩余工件。

4) Autogenerated code uses scoping to simplify the creation of several similar components with identical variable names (ie consider a gui generator that needed to make code for 100 radio buttons - rather than incrementing variable names per button, it could use scoping). 4) 自动生成的代码使用范围来简化多个具有相同变量名称的类似组件的创建(即考虑需要为 100 个单选按钮制作代码的 gui 生成器 - 而不是每个按钮增加变量名称,它可以使用范围)。

5) As a tiny, reusable, pastable logical block with minimal side effects : the programmer felt like a block of code in a method was so obscure, its variables and internal side effects should have minimal visibility to the outside world. 5) 作为一个微小的、可重用的、可粘贴的具有最小副作用的逻辑块:程序员觉得方法中的代码块是如此晦涩,它的变量和内部副作用应该对外界的可见性最小。 That is, the programmer has used a code block as a poor-man's anonymous lambda function (albeit, one without a return value).也就是说,程序员将代码块用作穷人的匿名 lambda 函数(尽管没有返回值)。 In this pattern one might do something akin to the below :在这种模式中,人们可能会做一些类似于以下的事情:

//lets say I want to make a primary key for a dogs name in a database. 
String dogNameKey=null;
{
    long time = System.currentTimeInMilliseconds();
    String theName = "spot";
    dogName=theName+"_"+time;
}

Clearly, the simple strategy for naming this record (dogNameKey) is not worthy of an external method - its too simple.显然,命名这条记录的简单策略(dogNameKey)配不上外部方法——它太简单了。 But at the same time, the "time" variable should have no bearing or accessibility outside the logic for making this name up - ie it shouldn't even be relevant to the method which contains this tiny key generating block.但与此同时,“时间”变量不应在构成此名称的逻辑之外没有任何意义或可访问性 - 即它甚至不应该与包含这个小密钥生成块的方法相关。 So, by using braces, I've scoped it out .所以,通过使用大括号,我已经确定了它的范围。 If a labmda were possible, than all of this scoping could be wrapped in a single, anonymous function.如果可以使用 labmda,那么所有这些作用域都可以包含在一个匿名函数中。

Now - I could paste several of these blocks, and the variable names would be identical, so it would be easy to scan them by eye.现在 - 我可以粘贴这些块中的几个,并且变量名称将是相同的,因此很容易通过肉眼扫描它们。

* Thus, when you see curly braces by themselves - they usually are pretty important - either they implement a specific custom-scoping, or they are an artifact of an error or potentially of autogenerated code. *因此,当您单独看到花括号时 - 它们通常非常重要 - 它们要么实现特定的自定义范围,要么是错误或潜在的自动生成代码的产物。 Scoping can also be used to "start" the refactoring of a method without actually writing a new method, by separating out its independant parts ... although IDEs are much better at this than humans.作用域也可用于“开始”重构方法,而无需实际编写新方法,通过分离其独立部分……尽管 IDE 在这方面比人类要好得多。 * *

It is called Block它被称为

A block is a sequence of statements, local class declarations and local variable declaration statements within braces.块是大括号内的语句序列、局部类声明和局部变量声明语句。

Also See:另见:

You can logically separate your code by this in some cases, and in fact there's one use case I apply very often: demo data.在某些情况下,您可以通过这种方式在逻辑上分离您的代码,事实上,我经常使用一个用例:演示数据。 Eg, you have some demo data generation class that creates demo data entries and inserts into your database.例如,您有一些演示数据生成类,用于创建演示数据条目并插入到您的数据库中。 You place each single item in such a block, and can do copy-paste without changing variable names.您将每个单个项目放在这样的块中,并且可以在不更改变量名称的情况下进行复制粘贴。

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

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