javatry-catchtry-with-resources

Unable to use the instance created in the try block from Main method in other static methods


I have a main method which consists of try-with-resource statement as follows -

public static void main(String[] args) throws Exception {
   try (final MaxApi api = new MaxApi(new CachedCurl(sw))) {

   final List<Values> finalValues = compute(); // Calls method outside of main method for compute
   final ValueClass value = new ValueClass(api);  // Instance api is used here
   ....
   ....
 }
}
private static List<Values> compute() {
final String request = "sample Request";
...
...
...
return secondMethod();    //calls second method for fetching values

private static List<Values> secondMethod() {

  return api.fetchResults();   //**Problem** I want to use the above created api instance here. But unable to use it. 

}

How can I use the above created instance of MaxApi in the method - "secondMethod" ?


Solution

  • Pass api as a parameter to compute(), and then have compute pass it as a parameter to secondMethod().