Gradle jar file variable type changed in java switch statements and getting error java.lang.NumberFormatException


(Enamul Quazi) #1

New to gradle, I have a method where codes are being changed in the jar file expecting String but getting negative numbers which throwing the exceptions. Why are the codes changing? What can be done to correct it? Any help will be appreciated.
Original code:
Browser(String browserType) {
Log.info(“Creating an instance of a “+browserType+” browser”);
switch (browserType) {
case Global.CHROME:
if (Global.REMOTE_EXECUTION){
ChromeDriverManager.getInstance().setup();
this.setDriver(new ChromeDriver());
}
break;
case Global.INTERNET_EXPLORER:
InternetExplorerDriverManager.getInstance().setup();
this.setDriver(new InternetExplorerDriver());
break;
default :
Log.info("Browser type not supported: "+browserType);
break;
}
}

Code in the jar:
Browser(String browserType) {
Log.info(“Creating an instance of a " + browserType + " browser”);
byte var3 = -1;
switch(browserType.hashCode()) {
case -1361128838:
if (browserType.equals(“chrome”)) {
var3 = 0;
}
break;
case 397430400:
if (browserType.equals(“internetexplorer”)) {
var3 = 1;
}
}

    switch(var3) {
    case 0:
        if (!Global.REMOTE_EXECUTION) {
            ChromeDriverManager.getInstance().setup();
            this.setDriver(new ChromeDriver());
        }
        break;
    case 1:
        InternetExplorerDriverManager.getInstance().setup();
        this.setDriver(new InternetExplorerDriver());
        break;
    default:
        Log.info("Browser type not supported: " + browserType);
    }

}

(James Justinic) #2

This observation has nothing to do with Gradle. This is how the Java compiler works. Support for using a String in a switch statement is just syntactic sugar. The compiler always converts a switch with a String into bytecode that does a switch on the int value of the hashCode() of the String. Decompiled bytecode almost always has noticeable differences from the original source.


(Enamul Quazi) #3

Thank you. In run time I need to pass browserType as String exp “chrome”, but decompiled code is expecting int. Is there a way to preserve the string format in bytecode? If not, any work around this?


(James Justinic) #4

There is no such thing as a switch on a String expression at the bytecode level. Notice that the original expression was replaced with browserType.hashCode(), which returns an int, so each case should also be an int. Specifically, those int values are the calculated hashCode() of each String value. Again, this is how the Java compiler works. This is not a problem and you can’t work around it. An exception might be thrown from your WebDriver code in the switch, but it’s not the switch itself.