2015-11-11 63 views
-1

我想將屬性加載到一些腳本中。從一個類加載屬性到另一個類

public class MyClass { 

    public static void myMethod() { 
     Properties prop = new Properties(); 

     InputStream config = Properties.class.getResourceAsStream("/config/config"); 
     try { 
      prop.load(config); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
     System.out.println(prop.getProperty("placeholder")); 

這將成功地打印出從/config/config文本文件中的控制檯值「佔位符」:當我做它像這樣它的工作原理。

我想使這更容易一些,實現一個數據抓取類,實現switch塊來區分不同的屬性文件。它看起來如下:

public class Data { 

    public static Properties getProperties(String file) { 
     Properties prop = new Properties(); 

     switch (file) { 
      case "config": 
       InputStream config = Properties.class.getResourceAsStream("/config/config"); 
       try { 
        prop.load(config); 
       } catch (IOException e) { 
        e.printStackTrace(); 
       } 
       break; 
     case "objectlocations": 
       InputStream objectlocations = Properties.class.getResourceAsStream("/properties/objectlocations"); 
       try { 
        prop.load(objectlocations); 
       } catch (IOException e) { 
        e.printStackTrace(); 
       } 
       break; 
     } 
     return prop; 
    } 
} 

有了這個類,根據我需要的屬性,我可以調用我想調用的文件。

這一切都檢查出來,直到我試圖把它放回MyClass.myMethod

public class MyClass { 

    public static void myMethod() { 
     Properties prop = new Properties(); 

     Data.getProperties("config"); 
     System.out.println(prop.getProperty("placeholder")); 

這樣實現它打印出「空」在控制檯,告訴我,性能也從沒收到過Data.getProperties("config");加載。

我需要使用getProperties方法添加,移動或移除以成功加載屬性,需要什麼?這是否是我的開關的問題,如果是這樣,我應該爲每個文件製作不同的方法?

在此先感謝。

+1

將行更改爲'prop = Data.getProperties(「config」);'Data.getProperties返回一個無處不在的屬性類型。你也可以做'屬性prop = Data.getProperties(「config」)'。 –

+0

@SaviourSelf很棒,非常感謝。如果你願意,你可以提出答案。 – jagdpanzer

+0

您應該認真考慮將參數類型設置爲'enum'而不是String。只要它是一個字符串,調用代碼就必須「知道」哪些字符串參數是有效的,哪些不是。 – VGR

回答

1

的問題是與以下幾行:

Properties prop = new Properties(); 
Data.getProperties("config"); 

的Data.getProperties行返回中包含您正在尋找的信息的屬性類型。您需要將該對象分配給本地Properties對象。

如果您將上述行更改爲Properties prop = Data.getProperties("config");,您將獲得要查找的對象。

相關問題