2011-11-21 110 views
0

每当我尝试按以下方法加载属性文件时。我得到原样使用Java加载属性文件

getClass()错误无法从Object类型

public static void main(String[] args) { 

     --- 
     --- 

    loadProperties(line); 

} 

private static void loadProperties(String line) { 
     Properties prop = new Properties(); 
     InputStream in = getClass().getResourceAsStream("foo.properties"); 
     try { 
      prop.load(in); 
      for(Object str: prop.keySet()) { 
       Object value = prop.getProperty((String) str); 
       System.out.println(str+" - "+value); 
      } 
      in.close(); 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 


    } 

任何建议,我怎么能解决这个使静态参考非静态方法的getClass()。

回答

3

您不能通过静态方法调用getClass。你要么需要做这在非静态方法:

class MyClass { 
    public static void main(String[] args) { 
     MyClass obj = new MyClass(); 
     obj.loadProperties(line);  
    } 

    private void loadProperties(String line) { 
     Properties prop = new Properties(); 
     InputStream in = getClass().getResourceAsStream("foo.properties"); 
     ... 
    } 
} 

或使用类文本,这确实在静态方面的工作,例如

InputStream in = MyClass.class.getResourceAsStream("foo.properties"); 
+1

需要注意的是,如果你使用'的getClass()',而不是一类的文字,有趣的事情可以在子类的存在下发生(你可能会得到与你想象的不同的包)。 – Thilo

2

访问属性文件,该文件是从静态方法usign项目类路径 getClass尝试,如:

import java.io.InputStream; 
import java.util.Properties; 
import java.io.IOException; 
public class HelperClass { 
    public static String getProperty() { 
     Properties properties = new Properties(); 
     String wadlURI = ""; 
      try { 
       InputStream inputStream = HelperClass.class.getClassLoader().getResourceAsStream("configuration.properties"); 
       properties.load(inputStream); 
       wadlURI = properties.getProperty("wadlurl"); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
      return wadlURI; 
     } 
}