简体   繁体   English

从不同的包访问变量

[英]Accessing Variable from different package

I want to access the variable in package 1 from package 2. 我想从包2中访问包1中的变量。

Class file TestDriver.java from package 1 包1中的类文件TestDriver.java

public class TestDriver {
private static TestDriver instance = new TestDriver();
private static int check;
private static int envt_num;
public static String envt,port,cpy_key;

public Connection con;
private ManageDBConnection mdbc;

private static String ENCRYPTION_KEY = "0123456789abcdef";

public void TestDriver(){
    check = 20;
    Properties prop = new Properties();
    String propFileName = "properties/environment.properties";
    try{
    InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(propFileName);
    System.out.println(inputStream);
    if (inputStream != null) {
        prop.load(inputStream);
        envt = prop.getProperty("envt");
        port = prop.getProperty("port");
        cpy_key = prop.getProperty("cpy_key");
        System.out.println("http://"+envt+"/netprofile/");  
        //Original Login Link
    /*  Constants.driver.get("http://"+prop.getProperty("user").replaceAll("\\s","")+":"+NP_Decrypt.getPassword().replaceAll("\\s","")+"@"+envt+"/netprofile/");
        inputStream.close();*/
        //Added for Local Testing
       String user = prop.getProperty("user");
       String password = prop.getProperty("password");
       Constants.driver.get("http://" + user + ":" + password + "@" + envt + "/test/");


    //  mdbc = new ManageDBConnection();
        //con = mdbc.CreateConnection();
    } else {
        throw new FileNotFoundException("property file '" + propFileName + "' not found in the classpath");
    }
    }catch(Exception e){
        e.printStackTrace();
    }   
}

} }

Class file Constants.java from package 2 包2中的类文件Constants.java

 public class Constants 
{
 static Properties prop = new Properties();
// propFileName = "properties/environment.properties";
//TestDriver testdriver = new TestDriver();
 static String envt = TestDriver.envt;
 static String cpy_key = TestDriver.cpy_key;


 //public static final 

 public static final WebDriver driver   = new FirefoxDriver();      

 public static final String InventorySummaryURL     ="http://"+envt+"/test/npHome.do?cpyKey="+cpy_key+"&custId=&grpId=0";    
 public static final String HomeSummary             ="http://"+envt+"/test/npIndex.do?cpyKey="+cpy_key+"&custId=&grpId=0";
 public static final String UploadStatus            ="http://"+envt+"/test/downloadModuleStatus.do?cpyKey="+cpy_key+"&custId=&grpId=0" ;
 public static final String ProfileStatus           ="http://"+envt+"/test/myProfileStatus.do?cpyKey="+cpy_key+"&custId=&grpId=0";

} }

In Constants.java the value returned for envt and cpy_key is zero. Constants.java ,为envtcpy_key返回的值为零。 I want the value from Package 1. 我想要包1中的值。

Main issue is that you're confusing static fields with instance fields, if the following variables: 主要问题是,如果使用以下变量,则会使静态字段与实例字段混淆:

private static final int check;
private static final int envt_num;
private static final String user, password;
public static String envt,port,cpy_key;

are the same across the JVM, don't modify them in a instance constructor, instead you can can create an static block to update the values of them and also, you can mark them as final if the are not supposed to be changed. 在JVM中是相同的,不要在实例构造函数中对其进行修改,而是可以创建一个静态块来更新它们的值,并且,如果不应该更改它们,则可以将它们标记为final

public final static String envt,port,cpy_key;

static {
    Properties prop = new Properties();
    String propFileName = "properties/environment.properties";
    try{
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(propFileName);
        System.out.println(inputStream);
        if (inputStream != null) {
           prop.load(inputStream);
           envt = prop.getProperty("envt");
           port = prop.getProperty("port");
           cpy_key = prop.getProperty("cpy_key");
          System.out.println("http://"+envt+"/netprofile/");  
          //Original Login Link
          /*        Constants.driver.get("http://"+prop.getProperty("user").replaceAll("\\s","")+":"+NP_Decrypt.getPassword().replaceAll("\\s","")+"@"+envt+"/netprofile/");
          inputStream.close();*/
          //Added for Local Testing
          user = prop.getProperty("user");
         password = prop.getProperty("password");

        } else {
         throw new FileNotFoundException("property file '" + propFileName + "' not found in the classpath");
        }
}

    public void TestDriver(){
         Constants.driver.get("http://" + user + ":" + password + "@" + envt + "/test/");


//  mdbc = new ManageDBConnection();
    //con = mdbc.CreateConnection();
}

The key is to separate what is static field vs what is an instance fields, the issue you had was the the static field wasn't being initialized when the class was loaded, but when the instance was created. 关键是要区分什么是静态字段,什么是实例字段,您遇到的问题是,在加载类时创建实例时并没有初始化静态字段。

  • Jose Luis 何塞·路易斯

The variables envt and cpy_key are declaired static but shouldn't be. 变量envt和cpy_key声明为静态,但不应为静态。 By declaring a variable to be static, you are telling the compiler/outside developers that this class doesn't have to be instantiated before you use that variable. 通过将变量声明为静态,可以告诉编译器/外部开发人员在使用该变量之前不必实例化此类。

In your code, the envt and cpy_key variables are only initialized in the constructor of the TestDriver class. 在您的代码中,envt和cpy_key变量仅在TestDriver类的构造函数中初始化。 When you reference them from another class without instantiating a TestDriver you are getting a null value which is sometimes mapped to 0. 当您从另一个类引用它们而没有实例化TestDriver时,您会得到一个值,该值有时映射为0。

What you can do is: 您可以做的是:

  1. Remove the static identifier from the envt and cpy_key variables, since you need to instantiate the TestDriver class before they able to be used. 从envt和cpy_key变量中删除静态标识符,因为需要先实例化TestDriver类,然后才能使用它们。
  2. Move the initialization code out of the constructor and use a static initialization block 将初始化代码移出构造函数,并使用静态初始化块

Example: 例:

public class TestDriver {
private static TestDriver instance = new TestDriver();
private static int check;
private static int envt_num;
public static String envt,port,cpy_key;

public Connection con;
private ManageDBConnection mdbc;

private static String ENCRYPTION_KEY = "0123456789abcdef";

static {
    check = 20;
    Properties prop = new Properties();
    String propFileName = "properties/environment.properties";
    try{
    InputStream inputStream = TestDriver.getClass().getClassLoader().getResourceAsStream(propFileName);
    System.out.println(inputStream);
    if (inputStream != null) {
        prop.load(inputStream);
        envt = prop.getProperty("envt");
        port = prop.getProperty("port");
        cpy_key = prop.getProperty("cpy_key");
        System.out.println("http://"+envt+"/netprofile/");  
        //Original Login Link
    /*      Constants.driver.get("http://"+prop.getProperty("user").replaceAll("\\s","")+":"+NP_Decrypt.getPassword().replaceAll("\\s","")+"@"+envt+"/netprofile/");
        inputStream.close();*/
        //Added for Local Testing
       String user = prop.getProperty("user");
       String password = prop.getProperty("password");
       Constants.driver.get("http://" + user + ":" + password + "@" + envt + "/test/");


    //  mdbc = new ManageDBConnection();
        //con = mdbc.CreateConnection();
    } else {
        throw new FileNotFoundException("property file '" + propFileName + "' not found in the classpath");
    }
    }catch(Exception e){
        e.printStackTrace();
    }   
}

So that fixes your initialization problem, but that doesn't solve your bigger class design problem. 这样可以解决您的初始化问题,但不能解决更大的类设计问题。 You should figure out a better (more Object Oriented) way of handling data. 您应该找出一种更好的(更面向对象的)数据处理方式。 You have two classes relying on each other's static variables. 您有两个依赖于彼此的静态变量的类。 This is a baaaad plan. 这是一个baaaad计划。 I would advise you to encapsulate the variables that need initializing and keep them in the TestDriver class. 我建议您封装需要初始化的变量,并将其保留在TestDriver类中。 Constants classes really should only be for things that you know ahead of time (hash key labels, numerical constants, etc). 常量类实际上仅应用于您事先知道的东西(哈希键标签,数字常量等)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM