2024-04-20 09:00:01

Java的隐藏特性

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


当前回答

大多数人不知道他们可以克隆一个数组。

int[] arr = {1, 2, 3};
int[] arr2 = arr.clone();

其他回答

可以使用枚举来实现接口。

public interface Room {
   public Room north();
   public Room south();
   public Room east();
   public Room west();
}

public enum Rooms implements Room {
   FIRST {
      public Room north() {
         return SECOND;
      }
   },
   SECOND {
      public Room south() {
         return FIRST;
      }
   }

   public Room north() { return null; }
   public Room south() { return null; }
   public Room east() { return null; }
   public Room west() { return null; }
}

编辑:多年后....

我在这里使用了这个特性

public enum AffinityStrategies implements AffinityStrategy {

https://github.com/peter-lawrey/Java-Thread-Affinity/blob/master/src/main/java/vanilla/java/affinity/AffinityStrategies.java

通过使用接口,开发人员可以定义自己的策略。使用枚举意味着我可以定义一个内置在一个中的集合(五个)。

The power you can have over the garbage collector and how it manages object collection is very powerful, especially for long-running and time-sensitive applications. It starts with weak, soft, and phantom references in the java.lang.ref package. Take a look at those, especially for building caches (there is a java.util.WeakHashMap already). Now dig a little deeper into the ReferenceQueue and you'll start having even more control. Finally grab the docs on the garbage collector itself and you'll be able to control how often it runs, sizes of different collection areas, and the types of algorithms used (for Java 5 see http://java.sun.com/docs/hotspot/gc5.0/gc_tuning_5.html).

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

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

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

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

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

不那么隐蔽,但很有趣。

你可以有一个没有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!!