我對Java編碼還很陌生,但我發現創建一個Debug
類並調用它非常有用,而不是進行很多System.out.println
調用。
我調試運行類是這個樣子..
Debug.java
public class Debug {
private static boolean debugActive = true;
public static void setDebug(boolean debug) {
Debug.debugActive = debug;
}
public static void print(String str) {
if (debugActive) {
StackTraceElement[] stacktrace = Thread.currentThread().getStackTrace();
StackTraceElement e = stacktrace[2];
String methodName = e.getMethodName();
System.out.print("[" + e + "]");
System.out.print(" => " + str);
System.out.println(" <= ");
}
}
public static void print(int x) {
print(x + "");
}
}
因此,從程序
DbIniParser.java調用它..
[...]
Debug.print(DB_User);
Debug.print(DB_Pass);
Debug.print(database);
Debug.print(host);
Debug.print(port);
[...]
主程序。
Debug.setDebug(true);
DbIniParser ini = new DbIniParser();
ini.readFile();
Debug.setDebug(false);
這提供了一個輸出..
控制檯輸出
[hospitalcase.DbIniParser.readFile(DbIniParser.java:35)] => hjess <=
[hospitalcase.DbIniParser.readFile(DbIniParser.java:36)] => password <=
[hospitalcase.DbIniParser.readFile(DbIniParser.java:37)] => myFunnyDatabase <=
[hospitalcase.DbIniParser.readFile(DbIniParser.java:38)] => localhost <=
[hospitalcase.DbIniParser.readFile(DbIniParser.java:39)] => 3306 <=
通過使用類本身的輸出可以改變爲日誌文件或別的東西。
請注意,我只在3個月內完成編程,所以這種方式可能不是最佳的,但我發現它相當有用,而不是每次都做System.out.print
。
對於調試,請使用調試器。對於單元測試,請使用單元測試框架。他們是不同的東西。 – 2011-12-17 08:46:57
並使用記錄器進行日誌記錄 – 2011-12-17 09:37:44
@pst感謝標題改變! – Strawberry 2011-12-17 12:37:55