Home > database >  Using variable from one method in another method
Using variable from one method in another method

Time:06-29

What I am trying to do is use the second method to create a pattern so that in the first method I only have to write the second method name with a parameter, in order to extract different values from a response body by passing the key-name as parameter.

The response from the second method displays an error "Cannot resolve symbol 'response'"

public class BDDStyledMethod {


    public static void GetActivityById(){

        Response response=Authentication.Creds("www.randomurl.com");
       
        System.out.println("The extracted thing is: "   bodyResponse("name"));

    }
    public static String bodyResponse(String exe){

       
        JsonPath jsonPathEvaluator = response.jsonPath();
        String bodyExample = jsonPathEvaluator.get(exe).toString();
        return bodyExample;
    }

CodePudding user response:

Aside: This is a java specific question, not an object-oriented question.

The crux of your question is about java scopes. The variable response is defined in the GetActivityById method. That method has a { and a }. That is the scope of the variable. What scope of a variable means, is that the variable is only visible - meaning, it only "exists" [1] after it was defined, [2] until the end of the scope (the curly brackets) it was defined in.

However, if you call a method, methodB from methodA, then methodB will have its own scope, which is separate from the scope of methodA which is the method calling it.

The method bodyResponse only has access to variables defined in its scope or passed into it as a parameter. So, to share a variable from one method to another, one way to do that is to pass it as a variable. You did this already with the exe variable. So, do the same for the response variable to fix this error:

public static void GetActivityById(){

        Response response=Authentication.Creds("www.randomurl.com");
       
        System.out.println("The extracted thing is: "   bodyResponse("name", response));//note I added *response*

    }
    public static String bodyResponse(String exe, Response response){//note I added *response*

       
        JsonPath jsonPathEvaluator = response.jsonPath();
        String bodyExample = jsonPathEvaluator.get(exe).toString();
        return bodyExample;
    }
  • Related