0
\$\begingroup\$

Consider the following two Java methods. The first takes a JSON string representing one element, the second representing multiple elements. gson.fromJson() can be called with a Class parameter or a Class[] parameter. The trick is in unifying the method signatures so a caller of creatBean() can call seamlessly with a Class or Class[] parameter. Is there a way these two can be combined?

public <T extends ValidateableBean>T createBean(String json, Class<T> clazz) {
    Gson gson = new Gson();
    T device = gson.fromJson(json, clazz);

    InputValidation inputValidation = new InputValidation();
    if (!inputValidation.validate((ValidateableBean) device, "Error during validation")) {
        throw new WebApplicationException(Status.BAD_REQUEST);
    }

    return device;
}

public <T extends ValidateableBean>T[] createBeans(String json, Class<T[]> clazz) {
    Gson gson = new Gson();
    T[] devices = gson.fromJson(json, clazz);

    InputValidation inputValidation = new InputValidation();
    for (T device : devices) {
        if (!inputValidation.validate((ValidateableBean) device, "Error during validation")) {
            throw new WebApplicationException(Status.BAD_REQUEST);
        }
    }

    return devices;
}
\$\endgroup\$
  • 1
    \$\begingroup\$ (Yes and no: Arbitrary Number of Arguments.) \$\endgroup\$ – greybeard Feb 15 at 9:26
  • \$\begingroup\$ @greybeard That's an idea. Are you sure there's no better way to overload a construction like this? \$\endgroup\$ – shasan Feb 15 at 18:57
  • \$\begingroup\$ Seeing your question for the first time, I took Class<T[]> clazz to be an error and Class<T>[] clazz to be intended - foolishly, I think revisiting this. I can't see varargs helping here - it just gives a slightly more pleasing syntax for zero to many "homogeneous" arguments specified individually. There's more to creating beans for one or several elements than call seamlessly: you get a variable number of results, too. \$\endgroup\$ – greybeard Feb 15 at 20:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.