2024-04-20 09:00:01

Java的隐藏特性

在阅读了c#的隐藏特性之后,我想知道Java的隐藏特性有哪些?


当前回答

逗号和数组。字符串s[] = { “123”, “234”, };

其他回答

在枚举中允许使用方法和构造函数让我感到惊讶。例如:

enum Cats {
  FELIX(2), SHEEBA(3), RUFUS(7);

  private int mAge;
  Cats(int age) {
    mAge = age;
  }
  public int getAge() {
    return mAge;
   }
}

你甚至可以有一个“常量特定类主体”,它允许特定的枚举值覆盖方法。

更多文档请点击这里。

strictfp关键字。(但我从未见过它在实际应用中使用:)

你可以使用下面的符号来获取基元类型的类: float.class等等。在做反射的时候非常有用。

Final数组可用于从匿名内部类中“返回”值(警告,下面的示例无用):

final boolean[] result = new boolean[1];
SwingUtilities.invokeAndWait(new Runnable() {
  public void run() { result[0] = true; }
});

一些控制流的技巧,最后围绕一个return语句:

int getCount() { 
  try { return 1; }
  finally { System.out.println("Bye!"); }
}

确定赋值规则将检查最终变量总是通过简单的控制流分析进行赋值:

final int foo;
if(...)
  foo = 1;
else
  throw new Exception();
foo+1;

我喜欢方法的静态导入。

例如,创建以下util类:

package package.name;

public class util {

     private static void doStuff1(){
        //the end
     }

     private static String doStuff2(){
        return "the end";
     }

}

然后像这样使用它。

import static package.name.util.*;

public class main{

     public static void main(String[] args){
          doStuff1(); // wee no more typing util.doStuff1()
          System.out.print(doStuff2()); // or util.doStuff2()
     }

}

静态导入适用于任何类,甚至数学…

import static java.lang.Math.*;
import static java.lang.System.out;
public class HelloWorld {
    public static void main(String[] args) {
        out.println("Hello World!");
        out.println("Considering a circle with a diameter of 5 cm, it has:");
        out.println("A circumference of " + (PI * 5) + "cm");
        out.println("And an area of " + (PI * pow(5,2)) + "sq. cm");
    }
}

我知道Java 6包括脚本支持,但我最近才发现jrunscript, 它可以交互式地解释和运行JavaScript(以及其他脚本语言,如Groovy),有点像Ruby中的Python shell或irb