Java反射 读取配置文件

Java反射可以用来读取配置文件,配置文件中存储着应用程序的一些配置信息,如数据库的连接信息、服务器的端口号、日志级别等。读取配置文件时,一般会将配置信息存储在一个 Properties 对象中,然后通过反射来获取对象的各种配置信息。

读取配置文件主要涉及两个类:Properties 类和 ClassLoader 类。Properties 类是用来读取配置文件的,而 ClassLoader 类则是用来加载类的。

以下是一个读取配置文件的示例代码:

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;

public class ConfigReader {
    private Properties properties;

    public ConfigReader(String configFile) {
        properties = new Properties();
        try {
            FileInputStream inputStream = new FileInputStream(configFile);
            properties.load(inputStream);
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public String getProperty(String key) {
        return properties.getProperty(key);
    }
}

上述代码中,ConfigReader 类用来读取配置文件,properties 对象用来存储配置信息,getProperty 方法用来获取某个配置项的值。在构造函数中,使用 FileInputStream 从配置文件中读取配置信息,并将其加载到 properties 对象中。

以下是一个使用 ConfigReader 类的示例代码:

public class MyApp {
    public static void main(String[] args) {
        ConfigReader configReader = new ConfigReader("config.properties");
        String url = configReader.getProperty("database.url");
        String username = configReader.getProperty("database.username");
        String password = configReader.getProperty("database.password");

        System.out.println("url: " + url);
        System.out.println("username: " + username);
        System.out.println("password: " + password);
    }
}

上述代码中,MyApp 类使用 ConfigReader 类来读取配置文件中的数据库连接信息,并将其输出到控制台上。

需要注意的是,上述代码中的配置文件名为 config.properties,并且配置文件必须放在类路径下才能被正确加载。

读取配置文件时,还可以使用 ClassLoader 类的 getResourceAsStream 方法来获取配置文件的输入流,如下所示:

InputStream inputStream = getClass().getClassLoader().getResourceAsStream("config.properties");

上述代码中,使用 getClass().getClassLoader().getResourceAsStream 方法获取配置文件的输入流,并将其加载到 properties 对象中。这种方法可以确保在不同的运行环境下都能正确读取到配置文件。