2024-04-20 09:00:01

Java的隐藏特性

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


当前回答

JDK 1.6_07+包含一个名为VisualVM (bin/jvisualvm.exe)的应用程序,它是许多工具之上的一个漂亮的GUI。它似乎比JConsole更全面。

其他回答

因为还没有人说过(我认为)我最喜欢的功能是自动装箱!

public class Example
{
    public static void main(String[] Args)
    {
         int a = 5;
         Integer b = a; // Box!
         System.out.println("A : " + a);
         System.out.println("B : " + b);
    }
}

还没有人提到instanceof的实现方式是不需要检查null的。

而不是:

if( null != aObject && aObject instanceof String )
{
    ...
}

只使用:

if( aObject instanceof String )
{
    ...
}

关闭钩子。这允许注册一个线程,该线程将立即创建,但仅在JVM结束时启动!因此,它是某种“全局jvm终结器”,您可以在这个线程中做一些有用的事情(例如关闭java资源,如嵌入式hsqldb服务器)。这适用于System.exit(),或CTRL-C / kill -15(当然,在unix上不适用kill -9)。

此外,它很容易设置。

            Runtime.getRuntime().addShutdownHook(new Thread() {
                  public void run() {
                      endApp();
                  }
            });;

当你不需要StringBuilder中包含的同步管理时,使用StringBuilder代替StringBuffer。它将提高应用程序的性能。

Java 7的改进甚至比任何隐藏的Java特性都要好:

菱形语法:Link

不要在实例化时使用那些infinite <>语法:

Map<String, List<String>> anagrams = new HashMap<String, List<String>>();

// Can now be replaced with this:

Map<String, List<String>> anagrams = new HashMap<>();

switch中的字符串:Link

在switch中使用String,而不是old-C int:

String s = "something";
switch(s) {
 case "quux":
    processQuux(s);
    // fall-through

  case "foo":
  case "bar":
    processFooOrBar(s);
    break;

  case "baz":
     processBaz(s);
    // fall-through

  default:
    processDefault(s);
    break;
}

自动资源管理Link

这段旧代码:

static void copy(String src, String dest) throws IOException {
    InputStream in = new FileInputStream(src);
    try {
        OutputStream out = new FileOutputStream(dest);
        try {
            byte[] buf = new byte[8 * 1024];
            int n;
            while ((n = in.read(buf)) >= 0)
                out.write(buf, 0, n);
        } finally {
            out.close();
        }
    } finally {
        in.close();
    }
}

现在可以用更简单的代码代替:

static void copy(String src, String dest) throws IOException {
    try (InputStream in = new FileInputStream(src);
            OutputStream out = new FileOutputStream(dest)) {
        byte[] buf = new byte[8192];
        int n;
        while ((n = in.read(buf)) >= 0)
            out.write(buf, 0, n);
    }
}

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

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

Java 5中的JConsole: Java 5中的JConsole

Java 6中的JConsole: Java 6中的JConsole

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