2024-04-20 09:00:01

Java的隐藏特性

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


当前回答

前面已经提到,final数组可用于将变量传递给匿名内部类。

另一种更好、更简洁的方法是使用java.util.concurrent.atomic包中的AtomicReference(或AtomicBoolean/AtomicInteger/…)类。

这样做的好处之一是,这些类还提供了compareAndSet这样的方法,如果要创建几个可以修改同一个变量的线程,这个方法可能很有用。


另一个有用的相关模式:

final AtomicBoolean dataMsgReceived = new AtomicBoolean(false);
final AtomicReference<Message> message = new AtomicReference<Message>();
withMessageHandler(new MessageHandler() {
    public void handleMessage(Message msg) {
         if (msg.isData()) {
             synchronized (dataMsgReceived) {
                 message.set(msg);
                 dataMsgReceived.set(true);
                 dataMsgReceived.notifyAll();
             }
         }
    }
}, new Interruptible() {
    public void run() throws InterruptedException {
        synchronized (dataMsgReceived) {
            while (!dataMsgReceived.get()) {
                dataMsgReceived.wait();
            }
        }
    }
});

在这个特殊的例子中,我们可以简单地等待message变成非空,但是null通常是一个有效值,然后你需要使用一个单独的标志来完成等待。

上面的waitMessageHandler(…)是另一个有用的模式:它在某个地方设置了一个处理程序,然后开始执行可能抛出异常的Interruptible,然后在finally块中删除该处理程序,如下所示:

private final AtomicReference<MessageHandler> messageHandler = new AtomicReference<MessageHandler>();
public void withMessageHandler(MessageHandler handler, Interruptible logic) throws InterruptedException {
    synchronized (messageHandler) {
        try {
            messageHandler.set(handler);
            logic.run();
        } finally {
            messageHandler.set(null);
        }
    }
}

这里我假设messageHandler的handleMessage(…)方法在接收到消息时被另一个线程调用。messageHandler不能简单地为messageHandler类型:这样您将同步一个正在变化的变量,这显然是一个错误。

当然,它不需要是InterruptedException,它可以是IOException之类的东西,或者在特定代码段中有意义的任何东西。

其他回答

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

来自Java 6的注释处理API看起来非常适合代码生成和静态代码验证。

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

而不是:

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

只使用:

if( aObject instanceof String )
{
    ...
}

当你不需要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);
    }
}

您可以使用string .format()构建sprintf样式的字符串。

String w = "world";
String s = String.format("Hello %s %d", w, 3);

当然,您也可以使用特殊的说明符来修改输出。

更多信息请点击:http://java.sun.com/j2se/1.5.0/docs/api/java/util/Formatter.html#syntax