无法从其他类访问类变量

时间:2016-12-22 09:18:26

标签: java

美好的一天!我有一个读取config.property文件的类,我需要从其他类访问该类的类变量。

将值从属性文件设置为类变量“gateway”的类:

SELECT *
FROM Course 
WHERE CourseID 
IN (Select CourseID 
        FROM Enrolment 
        GROUP BY CourseID
        HAVING COUNT(CourseID) > 1) 

从ReadPropertyFile类返回值的类:

此方法返回null:

    public class ReadPropertyFile {
    private String gateway;

    public static void main(String[] args) {
        ReadPropertyFile propCls = new ReadPropertyFile();
        propCls.setVlue();

    }

    public void setValue(){
        Properties prop = new Properties();

        try (InputStream input = new FileInputStream("config.properties")) {

            // load a properties file
            prop.load(input);

        } catch (IOException ex) {
            ex.printStackTrace();
        }

        // get the property value and print it out
        gateway = prop.getProperty("gateway");

    }

    public String getGateway() {
        return this.gateway;
    }
}

此方法返回我的属性:

public class getVariable{
    public static ReadPropertyFile propCls = new ReadPropertyFile();
    public static String gateway = propCls.getGateway();
    public static void main(String[] args) {

        System.out.println(gateway);
    }
}
  1. 在getVariable方法的第一个示例中,我尝试将值从属性文件设置为我的类变量,这是我的主要问题。
  2. 在第二个示例中,我在主类中创建了一个类对象,然后调用setValue方法并返回我的网关属性,而不调用setValue方法,类getVariable也返回null。
  3. 有人可以解释我需要如何从第一个样本重写我的类,将ReadPropertyFile类的值设置为类变量getVariable类。

    为什么我需要从getVariable类调用setValue方法来返回我的网关属性值。

    谢谢!

2 个答案:

答案 0 :(得分:0)

您的第一个示例不起作用,因为不会从任何地方调用setValue方法。为了使您的第一个示例正常工作,您必须将默认构造函数添加到 ReadPropertyFile 类,您可以在其中调用方法setValue()。

public class ReadPropertyFile {
    private String gateway;

    public ReadPropertyFile() {
        setValue();

    }

    public void setValue(){
        Properties prop = new Properties();

        try (InputStream input = new FileInputStream("config.properties")) {

            // load a properties file
            prop.load(input);

        } catch (IOException ex) {
            ex.printStackTrace();
        }

        // get the property value and print it out
        gateway = prop.getProperty("gateway");

    }

    public String getGateway() {
        return this.gateway;
    }
}

答案 1 :(得分:0)

如果以类getVariable作为主类运行程序,它将执行类getVariable的main方法,而不是类ReadPropertyFile的main方法。

解决此问题的一种方法是在类ReadPropertyFile的构造函数中调用setValue。另一种方式(更好的恕我直言)将在ReadPropertyFile中声明一个静态方法,它将创建一个实例,并调用setValue。

请注意,您在类名中使用动词的事实,是设计中出现问题的气味。

相关问题