2024-04-20 09:00:01

Java的隐藏特性

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


当前回答

前几天我对实例初始化器感到惊讶。我删除了一些代码折叠方法,最终创建了多个实例初始化器:

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

执行main方法将显示:

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

我想,如果您有多个构造函数并且需要通用代码,那么这些将很有用

它们还提供了初始化类的语法糖:

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

Map<String,String> codes = new HashMap<String,String>(){{ 
  put("1","one"); 
  put("2","two");
}};

其他回答

对于我面试的大多数Java开发人员来说,标记为块的职位是非常令人惊讶的。这里有一个例子:

// code goes here

getmeout:{
    for (int i = 0; i < N; ++i) {
        for (int j = i; j < N; ++j) {
            for (int k = j; k < N; ++k) {
                //do something here
                break getmeout;
            }
        }
    }
}

谁说goto在java中只是一个关键字?:)

javabean属性访问器方法不必以“get”和“set”开头。

甚至Josh Bloch在《Effective Java》中也犯了这个错误。

当我第一次注意到三元运算符等于一个简单的if-then-else语句时,我很惊讶:

minVal = (a < b) ? a : b;

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).

Javadoc——在正确编写的情况下(不幸的是,一些开发人员并不总是这样),它会为您提供一个清晰、连贯的描述,说明代码应该做什么,而不是它实际做什么。然后可以将其转换为一组不错的可浏览的HTML文档。如果你使用持续集成等方法,它可以定期生成,这样所有开发者都可以看到最新的更新。