看上去一個(gè)很簡(jiǎn)單的問題,結(jié)果卻不是想象中的那樣。良好的編碼習(xí)慣是多么的重要啊。
測(cè)試的代碼如下:
public class TestPrintStream1 {
public static void main(String[] args) {
Class c = TestPrintStream1.class;
try {
Object o = c.newInstance();
if (o instanceof TestPrintStream1)
TestPrintStream1 tt = (TestPrintStream1) o;// 這里為什么會(huì)報(bào)錯(cuò)呢,說tt 和 TestPrintStream1不能不解析
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
那一行為什么會(huì)報(bào)錯(cuò)呢?if語句后面不是允許不加大括號(hào)嗎?
if ()
后面不使用花括號(hào)時(shí),里面不能出現(xiàn)聲明,因?yàn)槟莻€(gè)涉及到作用域,而沒有花括號(hào)又沒有作用域了??荚嚧缶庉嬂斫?。
boolean ok = true;
if(ok)
MyClass c = new MyClass();
這樣也是不允許的。
改成
MyClass c = null;
if(ok)
c = new MyClass();
這樣是可以的
這個(gè)代碼問題和 instanceof 沒有任何關(guān)系
Java 把 Test tt = new Test(); 當(dāng)兩條語句看待了相當(dāng)于 Test tt; tt = new Test();
測(cè)試的代碼如下:
public class TestPrintStream1 {
public static void main(String[] args) {
Class c = TestPrintStream1.class;
try {
Object o = c.newInstance();
if (o instanceof TestPrintStream1)
TestPrintStream1 tt = (TestPrintStream1) o;// 這里為什么會(huì)報(bào)錯(cuò)呢,說tt 和 TestPrintStream1不能不解析
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
那一行為什么會(huì)報(bào)錯(cuò)呢?if語句后面不是允許不加大括號(hào)嗎?
if ()
后面不使用花括號(hào)時(shí),里面不能出現(xiàn)聲明,因?yàn)槟莻€(gè)涉及到作用域,而沒有花括號(hào)又沒有作用域了??荚嚧缶庉嬂斫?。
boolean ok = true;
if(ok)
MyClass c = new MyClass();
這樣也是不允許的。
改成
MyClass c = null;
if(ok)
c = new MyClass();
這樣是可以的
這個(gè)代碼問題和 instanceof 沒有任何關(guān)系
Java 把 Test tt = new Test(); 當(dāng)兩條語句看待了相當(dāng)于 Test tt; tt = new Test();