2024-04-20 09:00:01

Java的隐藏特性

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


当前回答

值:

new URL("http://www.yahoo.com").equals(new URL("http://209.191.93.52"))

是真的。

(摘自Java Puzzlers)

其他回答

不那么隐蔽,但很有趣。

你可以有一个没有main方法的"Hello, world"(它会抛出NoSuchMethodError思想)

最初由RusselW在最奇怪的语言功能上发布

public class WithoutMain {
    static {
        System.out.println("Look ma, no main!!");
        System.exit(0);
    }
}

$ java WithoutMain
Look ma, no main!!

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

而不是:

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

只使用:

if( aObject instanceof String )
{
    ...
}

您可以使用Class<T>对象添加泛型类型的运行时检查,当在某个配置文件中创建类且无法为类的泛型类型添加编译时检查时,这非常方便。你不希望类在运行时爆炸,如果应用程序碰巧配置错误,你不希望所有的类都充满了检查的实例。

public interface SomeInterface {
  void doSomething(Object o);
}
public abstract class RuntimeCheckingTemplate<T> {
  private Class<T> clazz;
  protected RuntimeChecking(Class<T> clazz) {
    this.clazz = clazz;
  }

  public void doSomething(Object o) {
    if (clazz.isInstance(o)) {
      doSomethingWithGeneric(clazz.cast(o));
    } else {
      // log it, do something by default, throw an exception, etc.
    }
  }

  protected abstract void doSomethingWithGeneric(T t);
}

public class ClassThatWorksWithStrings extends RuntimeCheckingTemplate<String> {
  public ClassThatWorksWithStrings() {
     super(String.class);
  }

  protected abstract void doSomethingWithGeneric(T t) {
    // Do something with the generic and know that a runtime exception won't occur 
    // because of a wrong type
  }
}

几年前,当我必须做Java (1.4.x)时,我想要一个eval()方法,而太阳javac是(是?)用Java编写的,所以它只是链接tools.jar,并使用它周围的一些胶水代码。

我今天才(重新)了解到$是Java中方法或变量的合法名称。与静态导入相结合,可以生成一些可读性稍强的代码,这取决于你对可读的看法:

http://garbagecollected.org/2008/04/06/dollarmaps/