Related to this question regarding static methods, but I didn't feel my question was clearly answered, as mine has a few details I'm unsure about.
I have a small handmade api class (just a .class, nothing fancy) who has a javax client object instantiated at the global level.
final private static Login login = new Login("emadden", "password");
final private static String baseUrl = "http://example.com";
private static Client client = ClientBuilder.newClient().register(JacksonJsonProvider.class);
private static WebTarget target;
private static Invocation.Builder builder;
private static Response response;
Because javax client objects are rather large, I wanted to keep myself and anyone else who might want to use the api from accidentally creating a bunch of these rather large client objects, so all of the attributes (including the client) and methods, with the exception of the api constructors, are static.
// example method
public static Response getFrom(String pathUrl) throws RuntimeException{
try {
target = (WebTarget) client.target(baseUrl).path(pathUrl); // TODO: remove cast
builder = target.request(MediaType.APPLICATION_JSON);
response = builder.get();
response.close();
if (response.getStatus() == 204) {
System.out.println("GET successful");
} else if (response.getStatus() != 200) {
throw new RuntimeException("Failed : HTTP error cod : "
+ response.getStatus());
}
} catch(RuntimeException e) {System.out.println(e.getMessage());}
return response;
}
Now then, in the class (main.class) that I'm using the api class in, is a global variable, an ArrayList named data, that is instantiated by a static method call to the api class as such.
// Global scope
private static ArrayList<List> data = api.getFrom(baseUrl + pathUrl).readEntity(ArrayList.class)
Nowhere is the api class instantiated in main, but the api.getFrom method does reference the api's global client object, so would that mean that simply calling this method creates an instance of the client object? Would calling it again somewhere else create another?
In the end, I just removed 'static' from the methods, kept the attributes static, allowing me to access the api non-statically with instance of the api in main, but I'm nervous about the possibility of someone creating an instance of the api, then passing it as a parameter, inadvertently creating a copy of it.
So, for knowledge sake, and possibly keeping what I described above from happening, what would happen when calling api.getFrom() from a static context, like I had done originally? Does it create instances of it's global variables, only to discard them once we're outside the scope of the method call? Did I do right just caving in and dropping static from the methods or is there a better way to ensure I, or another user won't be accidentally creating instances of the api and a bunch of big client objects?