我有基于以下代码的问题:
public class LoginCaptchaChrome {
public static void main(String[] args) throws IOException, InterruptedException{
String tc = args[0];
String address = args[1];
String test_data = args[2];
String test_result = args[3];
System.setProperty("webdriver.chrome.driver", "C:\\Users\\Lam Chio Meng\\Desktop\\work\\chromedriver_win32\\chromedriver.exe");
//Do other stuff
}
//runTest is called from a different class
public static void runTest(String string0, String string, String string1) throws InterruptedException, IOException{
WebDriver login = new ChromeDriver();
System.out.println(login);
login.get(address);
//Do other things
}
}
我从通过命令提示符执行期间传递的参数获取 tc,address,test_data
和 test_result
的值。现在,我想将 address
值传递给位于 runTest 方法中的 login.get(address)
。
我现在无法做到这一点,因为我知道要发生这种情况,必须在 main 方法之外声明变量 address
。我无法在 main 方法之外声明 address
变量,因为它正在从命令提示符接收争论。请记住,方法 runTest 已被指定为接受来自不同类的另一个方法的值。希望大家就如何将 main 方法中的 address
值传递到 runTest 方法中的 address
变量提供建议。
最佳答案
您可以在类LoginCaptchaChrome
中声明一个字段。声明一个可以在 main 方法中访问的静态字段。
请记住,非静态字段需要类(对象)的实例才能访问,静态字段不需要实例,并且可以通过静态上下文访问。
现在一些代码示例:
public class LoginCaptchaChrome {
public static Optional<String> addressOptional = Optional.empty
public static void main(String[] args) throws IOException, InterruptedException{
String tc = args[0];
String address = args[1];
String test_data = args[2];
String test_result = args[3];
//using Optional since it will simply handling value not present cases
addressOptional = Optional.of(args[4]);
System.setProperty("webdriver.chrome.driver", "C:\\Users\\Lam Chio Meng\\Desktop\\work\\chromedriver_win32\\chromedriver.exe");
//Do other stuff
}
//runTest is called from a different class
public static void runTest(String string0, String string, String string1) throws InterruptedException, IOException{
WebDriver login = new ChromeDriver();
System.out.println(login);
//Using this you throw an error when no address is supplied via cmd ,
//if address is supplied then you will get it here
login.get(addressOptional.orElseThrow(()->new NoSuchElement("address is not provided")))
//Do other things
}
}
如果您不熟悉java 8中的可选内容,它可以帮助您避免空值并采用更实用的方法。
关于java - 从主方法调用变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39031106/