Hidden Features of Java

在阅读C#隐藏特性之后,我想知道,Java的一些隐藏特性是什么?


Double Brace Initialization took me by surprise a few months ago when I first discovered it, never heard of it before.

ThreadLocals are typically not so widely known as a way to store per-thread state.

Since JDK 1.5 Java has had extremely well implemented and robust concurrency tools beyond just locks, they live in java.util.concurrent and a specifically interesting example is the java.util.concurrent.atomic subpackage that contains thread-safe primitives that implement the compare-and-swap operation and can map to actual native hardware-supported versions of these operations.


Joint union in type parameter variance:

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

For example, if you wanted to take a parameter that's both Comparable and a Collection:

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);
}

This contrived method returns true if the two given collections are equal or if either one of them contains the given element, otherwise false. The point to notice is that you can invoke methods of both Comparable and Collection on the arguments b1 and b2.


I was surprised by instance initializers the other day. I was deleting some code-folded methods and ended up creating multiple instance initializers :

public class App {
    public App(String name) { System.out.println(name + "'s constructor called"); }

    static { System.out.println("static initializer called"); }

    { System.out.println("instance initializer called"); }

    static { System.out.println("static initializer2 called"); }

    { System.out.println("instance initializer2 called"); }

    public static void main( String[] args ) {
        new App("one");
        new App("two");
  }
}

Executing the main method will display:

static initializer called
static initializer2 called
instance initializer called
instance initializer2 called
one's constructor called
instance initializer called
instance initializer2 called
two's constructor called

I guess these would be useful if you had multiple constructors and needed common code

They also provide syntactic sugar for initializing your classes:

List<Integer> numbers = new ArrayList<Integer>(){{ add(1); add(2); }};

Map<String,String> codes = new HashMap<String,String>(){{ 
  put("1","one"); 
  put("2","two");
}};
链接地址: http://www.djcxy.com/p/14456.html

上一篇: JVM标志CMSClassUnloadingEnabled实际上做了什么?

下一篇: Java的隐藏特性