[英]How can I use a public variable outside a method in two different class files?
I have 2 Class files.我有 2 个类文件。 Class_login.java and Class_Company.java. Class_login.java 和 Class_Company.java。 I have an xpath stored in different location in a properties file.我有一个 xpath 存储在属性文件的不同位置。 A method is written in Class_login.java to load this properties file.在 Class_login.java 中编写了一个方法来加载此属性文件。
static Properties objprop1 = new Properties();
public static FileInputStream fileInputS = null;
static void propManager() throws IOException {
fileInputS = new FileInputStream("C:\\Test-Automation\\FinanceSys\\myproj\\src\\test\\resources\\xpath.properties");
objprop1.load(fileInputS);
}
objprop1
is declared outside the method in Class_login.java
. objprop1
在Class_login.java
的方法外声明。
I need to load this file again in Class_Company.java
.我需要在Class_Company.java
中再次加载此文件。 If I use it like Class_login.PropertyManager();
如果我像Class_login.PropertyManager();
这样使用它and use same objprop1 the file does not load and the xpaths are not found.并使用相同的 objprop1 文件不会加载并且找不到 xpaths。
Hence I created same method with a different name( static void PropertyManager() {
) and因此,我创建了具有不同名称的相同方法( static void PropertyManager() {
)和public static Properties objprop = new Properties();
I know this is not the correct way.我知道这不是正确的方法。 But how can this be done otherwise?但是,否则怎么办呢? In the main method of Class_Company.java
I called these methods separately so that I do not get a null xpath error as earlier.在Class_Company.java
的主要方法中,我分别调用了这些方法,这样我就不会像之前那样得到 null xpath 错误。
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
Class_login LogFeature = new Login();
Class_Company CC = new CCompany();
**Class_Company.PropertyManager();**
LogFeature.OpenBrowser("CH32");
LogFeature.EnterURL("http://localhost:90/AppFin");
LogFeature.PageMaximise();
LogFeature.EnterUserName("uname");
LogFeature.EnterPassword("abcd!@");
LogFeature.ClickLoginButton();
Thread.sleep(2000);
**Class_Company.propManager();**
CC.clickNewCompany("Manage");
Please tell me the right way of doing it.请告诉我正确的做法。 I want to use objprop in both the class files and only once in Class_Company.java.我想在两个类文件中都使用 objprop,并且只在 Class_Company.java 中使用一次。 and not twice as highlighted above.而不是上面强调的两倍。
This is the basic example, which you need:这是您需要的基本示例:
Global Variable declaration:全局变量声明:
Class variableCollection {
public static string data;
}
You can use this variables by extending class Or object references.您可以通过扩展类或对象引用来使用此变量。
class login extends variableCollection{
}
OR要么
class login{
variableCollection objvar = new variableCollection();
objvar.data = "";
}
You can use this same variable in multiple classes, same way.您可以在多个类中以相同的方式使用同一个变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.