2012-11-03 18 views
-1

我需要使用设置一些全局变量,这些变量将被几个类使用。从属性文件设置静态变量java

我无法从属性文件中分配静态变量。

我想调用变量是这样的:String url = WebdriverConfiguration.getBaseUrl();

public class WebDriverConfiguration 
{ 
    private static Properties testProperties; 
    private static String instaceUrl; 

    testProperties = loadProperties(); 


    public static final String DEFAULT_BASEURL = testProperties.getProperty("confluence.base.url",""); 
    private static final int DEFAULT_HTTP_PORT = 8080; 
    private static final String DEFAULT_CONTEXT_PATH = "/"; 
    public static final String TEST_SPACE_KEY = "SMOKE"; 
    public static final String TEST_PAGE = "XXX"; 

    private static final String BASE_URL = System.getProperty("baseurl", DEFAULT_BASEURL); 


    public static String getBaseUrl() 
    { 
     return BASE_URL; 

    } 



    private Properties loadProperties() throws IOException 
{ 
    InputStream testPropertiesInput = getClass().getClassLoader().getResourceAsStream("webtester.properties"); 
    Properties testProperties = new Properties(); 

    if (null != testPropertiesInput) 
    { 
     try 
     { 
      testProperties.load(testPropertiesInput); 
     } 
     finally 
     { 
      IOUtils.closeQuietly(testPropertiesInput); 
     } 
    } 
    return testProperties; 
} 


    } 
+0

问题是什么? –

+0

想从该属性文件分配静态变量,看看有一些静态变量,我想从属性中获得一些。加载是好的,只是无法从另一个类实例化它。 – user979587

回答

4

我不确定你在这里问什么,但你提供的代码不应该编译。更换

private static Properties testProperties; 
testProperties = loadProperties(); 

private static final Properties testProperties = loadProperties(); 

更新,发现annother错误。你也必须改变的loadProperties方法签名:

private static final Properties loadProperties() throws IOException {...} 

     ^ ^
+0

loadProperties需要'静态',也不能抛出检查异常 –

+0

@Tim Bender:刚才也意识到 - 看到我的更新。 – home

+0

在getClass()表示不是静态方法时抛出错误 – user979587

1

使用中的问题目前的设计,以下更改需要进行:

public class WebDriverConfiguration { 
    private static Properties testProperties = loadProperties(); 
    //...snip... 

    private static Properties loadProperties() { //must be static and can not throw a checked exception 
    //...snip... 
    } 
} 
+0

会使我从另一个班级调用它吗? – user979587

0

我想你务必做好这一点:

首先,让你的构造函数签名为private。 其次,将你的loadProperties()放到静态块中。第三,你应该把你所有的财产私有。