在Jonathan Skeet的final variable passed to anonymous class via constructor中提到變量通過自動生成的構造函數傳遞給匿名類實例。爲什麼我無法看到在這種情況下使用反射構造:將最終變量傳遞給匿名類
public static void main(String... args) throws InterruptedException {
final int x = 100;
new Thread() {
public void run() {
System.out.println(x);
for (Constructor<?> cons : this.getClass()
.getDeclaredConstructors()) {
StringBuilder str = new StringBuilder();
str.append("constructor : ").append(cons.getName())
.append("(");
for (Class<?> param : cons.getParameterTypes()) {
str.append(param.getSimpleName()).append(", ");
}
if (str.charAt(str.length() - 1) == ' ') {
str.replace(str.length() - 2, str.length(), ")");
} else
str.append(')');
System.out.println(str);
}
}
}.start();
Thread.sleep(2000);
}
輸出是:
100
constructor : A$1()
@Bohemian:鑑於我知道問題的由來,我認爲它是:) –