[英]Static String path in Java
我的小程序只有一個主類,它使用了很多路徑。 由於它們在程序運行時不會改變,我想我可以在它們的聲明中加入static
,但不確定最終聲明。 此外,我不確定聲明路徑的最佳位置在哪里。 是在班上還是在班上?
這是我的代碼示例:
package classtest;
public class ClassTest {
// Should I put the path here?
public static void main(String[] args) {
String dirPath = "C:/Users/test1/";
String pathOut = "C:/Users/stats.csv";
// or here?
}
}
另一種方法是從屬性文件中讀取路徑:
Properties prop = new Properties();
並隨便使用屬性。 這使得以后的重構非常容易:
prop.getProperty("diPath");
prop.getProperty("pathOut");
設置路徑參數更為常見,因此可以由運行該程序的人設置。
public class ClassTest {
public static void main(String[] args) {
if (args.length < 2) {
System.err.println("Usage: java ClassTest {dir} {output}");
return;
}
String dirPath = args[0];
String pathOut = args[1];
}
}
final
關鍵字表示永遠不會重新分配該值。
static
關鍵字使該變量為類變量,而不是實例變量。
另外要注意的是,通常用下划線定界符大寫類常量,因此我更改了名稱。
因此,如果您想“全局”聲明它們,最好的方法是使用類似於以下內容的代碼。
public class ClassTest {
public static final String DIR_PATH = "C:/Users/test1/";
public static final String PATH_OUT = "C:/Users/stats.csv";
public static void main(String[] args) {
// Use DIR_PATH or PATH_OUT as needed
}
}
請注意,僅當您以不同的方法重用DIR_PATH
或PATH_OUT
變量時,以上代碼才有用。 否則,將變量定義為main方法的局部變量是正確的,以將可見性限制為使用它的代碼的唯一部分。
您可以執行這種重構:
public class ClassTest {
// Specify a base path for all paths to be used
public static final String BASE_PATH = "C:/Users";
// 1. If these paths will be used in several methods, declare them here
public static final String dirPath = BASE_PATH + "/test1/";
public static final String pathOut = BASE_PATH + "/stats.csv";
public static void main(String[] args) {
// 2. If those paths will be used in the main method only, declare them here
final String dirPath = BASE_PATH + "/test1/";
final String pathOut = BASE_PATH + "/stats.csv";
}
}
類的靜態成員應在任何類方法的范圍之外聲明。
試試這個..這是最干凈的方法:
public class ClassTest implements StaticPath {
public static void main(String[] args) {
System.out.print(PATH_OUT);
}
}
interface StaticPath {
public final static String PATH = "C:/Users/";
public final static String PATH_OUT = PATH + "stats.csv";
public final static String PATH_IN = PATH + "dyn.csv";
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.