2024-04-20 09:00:01

Java的隐藏特性

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


当前回答

这并不是一个真正的功能,而是我最近在一些网页上发现的一个有趣的技巧:

class Example
{
  public static void main(String[] args)
  {
    System.out.println("Hello World!");
    http://Phi.Lho.free.fr

    System.exit(0);
  }
}

是一个有效的Java程序(尽管它会生成警告)。 如果你不明白为什么,请看格雷戈里的回答!;-)好吧,这里的语法高亮也给了一个提示!

其他回答

类型参数方差的联合:

public class Baz<T extends Foo & Bar> {}

例如,如果你想取一个参数,它既是可比的又是集合的:

public static <A, B extends Collection<A> & Comparable<B>>
boolean foo(B b1, B b2, A a) {
   return (b1.compareTo(b2) == 0) || b1.contains(a) || b2.contains(a);
}

如果两个给定的集合相等,或者其中任何一个包含给定元素,则该方法返回true,否则返回false。需要注意的一点是,您可以对参数b1和b2调用Comparable和Collection方法。

显然,在一些调试版本中,有一个从HotSpot: http://weblogs.java.net/blog/kohsuke/archive/2008/03/deep_dive_into.html转储本机(JIT)程序集代码的选项

不幸的是,我无法通过那篇文章中的链接找到构建,如果有人能找到一个更精确的URL,我很乐意使用它。

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

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

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

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

部分功能,部分麻烦:Java的String处理使其“看起来”是原生类型(使用运算符,+,+=)

能写的:

String s = "A";
s += " String"; // so s == "A String"

非常方便,但只是语法糖(即被编译为):

String s = new String("A");
s = new StringBuffer(s).append(" String").toString();

因此,一个对象实例化和2个方法调用一个简单的连接。想象一下以这种方式在循环中构建一个长字符串!?并且StringBuffer的所有方法都声明为同步的。谢天谢地,在Java 5中,他们引入了StringBuilder,它与StringBuffer是一样的,只是没有同步。

这样的循环:

String s = "";
for (int i = 0 ; i < 1000 ; ++i)
  s += " " + i; // Really an Object instantiation & 3 method invocations!

可以(应该)在你的代码中重写为:

StringBuilder buf = new StringBuilder(); // Empty buffer
for (int i = 0 ; i < 1000 ; ++i)
  buf.append(' ').append(i); // Cut out the object instantiation & reduce to 2 method invocations
String s = buf.toString();

并将运行大约80+%比原来的循环! (在我运行的一些基准测试中高达180%)

没读到过

Integer a = 1;
Integer b = 1;
Integer c = new Integer(1);
Integer d = new Integer(1);

Integer e = 128;
Integer f = 128;

assertTrue (a == b);   // again: this is true!
assertFalse(e == f); // again: this is false!
assertFalse(c == d);   // again: this is false!

通过搜索java的整数池(内部“缓存”从-128到127用于自动装箱)或查看integer . valueof来了解更多信息