Java 将属性从一个类加载到另一个类中

Java 将属性从一个类加载到另一个类中,java,properties,Java,Properties,我正在尝试将属性加载到一些脚本中。当我这样做时,它会起作用: public class MyClass { public static void myMethod() { Properties prop = new Properties(); InputStream config = Properties.class.getResourceAsStream("/config/config"); try { pro

我正在尝试将属性加载到一些脚本中。当我这样做时,它会起作用:

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
文本文件中成功打印出值“placeholder”

我想让这变得简单一点,并实现一个数据捕获类,实现一个
开关
块来区分不同的属性文件。如下所示:

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"));
像这样实现它会在控制台中打印出“null”,告诉我属性从未从
Data.getProperties(“config”)加载

要使用
getProperties
方法成功加载属性,我需要添加、移动或删除什么?我的开关有问题吗?如果有问题,我应该为每个文件使用不同的方法吗


提前感谢。

问题在于以下几行:

Properties prop = new Properties();
Data.getProperties("config");
Data.getProperties行返回一个属性类型,其中包含您要查找的信息。您需要将该对象指定给本地属性对象


如果将上述行更改为
Properties prop=Data.getProperties(“config”)
,您将得到您要查找的对象。

将行更改为
prop=Data.getProperties(“config”)
Data.getProperties返回一个不存在的属性类型。您也可以执行
Properties prop=Data.getProperties(“config”)
。@SaviourSelf工作得很好,非常感谢。如果你愿意的话,你可以把答案扔到上面。你应该认真考虑把这个参数类型化为<代码> EnUM<代码>而不是字符串。只要是字符串,调用代码就必须“知道”哪些字符串参数有效,哪些无效。