2024-04-20 09:00:01

Java的隐藏特性

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


当前回答

"const"是一个关键字,但你不能使用它。

int const = 1;   // "not a statement"
const int i = 1; // "illegal start of expression"

我猜编译器的作者认为将来可能会用到它,他们最好保留它。

其他回答

您可以定义一个匿名子类,并直接调用它上的方法,即使它没有实现接口。

new Object() {
  void foo(String s) {
    System.out.println(s);
  }
}.foo("Hello");

我喜欢方法的静态导入。

例如,创建以下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");
    }
}

我可以添加扫描仪对象。它是解析的最佳选择。

String input = "1 fish 2 fish red fish blue fish";
Scanner s = new Scanner(input).useDelimiter("\\s*fish\\s*");
System.out.println(s.nextInt());
System.out.println(s.nextInt());
System.out.println(s.next());
System.out.println(s.next());
s.close();

Javadoc——在正确编写的情况下(不幸的是,一些开发人员并不总是这样),它会为您提供一个清晰、连贯的描述,说明代码应该做什么,而不是它实际做什么。然后可以将其转换为一组不错的可浏览的HTML文档。如果你使用持续集成等方法,它可以定期生成,这样所有开发者都可以看到最新的更新。

作为初学者,我非常欣赏Java 6中的JConsole监控软件,它已经为我解决了一些问题,而且我还在不断地寻找它的新用途。

显然JConsole在Java 5中已经有了,但我认为现在它已经改进了,至少现在工作得更稳定了。

Java 5中的JConsole: Java 5中的JConsole

Java 6中的JConsole: Java 6中的JConsole

当你在做它的时候,好好看看本系列中的其他工具: java6故障排除工具