2024-04-20 09:00:01

Java的隐藏特性

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


当前回答

使用静态导入,你可以做一些很酷的事情,比如:

List<String> myList = list("foo", "bar");
Set<String> mySet = set("foo", "bar");
Map<String, String> myMap = map(v("foo", "2"), v("bar", "3"));

其他回答

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

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 cmd/控制台窗口中按CTRL-Break键

unix: kill -3 PID

他们花了足够长的时间来增加支持,

系统托盘

JDK 1.6_07+包含一个名为VisualVM (bin/jvisualvm.exe)的应用程序,它是许多工具之上的一个漂亮的GUI。它似乎比JConsole更全面。

一些控制流的技巧,最后围绕一个return语句:

int getCount() { 
  try { return 1; }
  finally { System.out.println("Bye!"); }
}

确定赋值规则将检查最终变量总是通过简单的控制流分析进行赋值:

final int foo;
if(...)
  foo = 1;
else
  throw new Exception();
foo+1;