0

I have a Servlet for handling Ajax requests which gives response in JSON-format.

I get this warning on line as commented below. Type safety: The method setResponseData(Object) belongs to the raw type JsonResponse. References to generic type JsonResponse should be parameterized

Should I be doing this another way, or is it safe to add SuppressWarning annotation

public class JsonResponse<T>
{
    private T responseData;
    private boolean success;
    private String errorMessage;
    // + Getters and Setters
}

public class AjaxJson extends HttpServlet
{
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    {
        String function = request.getParameter("func");
        if (function == null)
            function = "";

        JsonResponse<?> jsonResponse;

        if (function.equals("getUsers"))
            getUsers(jsonResponse);
    }

    private void getUsers(JsonResponse jsonResponse)
    {
        jsonResponse = new JsonResponse<List<User>>();

        // Lets say I have a class called User
        List<User> users = new ArrayList<Users>();
        // get users and add to list

        jsonResponse.setResponseData(users); // Warning on this line
        jsonResponse.setSuccess(true);
    }
}
user2864740
  • 60,010
  • 15
  • 145
  • 220
sjallamander
  • 439
  • 2
  • 6
  • 20

2 Answers2

2

You are using JsonResponse as a generic

private void getUsers(JsonResponse jsonResponse)

change it to

private void getUsers(JsonResponse<List<User>> jsonResponse)

Java always warn about using generics and for more information look at this question on SO.

Community
  • 1
  • 1
Mohsen Kamrani
  • 7,177
  • 5
  • 42
  • 66
  • Yes, at least the warning is gone now. But now I get compile error on getUsers(jsonResponse): The method getUsers(JsonResponse) in the type AjaxJson is not applicable for the arguments (JsonResponse) – sjallamander Apr 16 '14 at 07:53
1

Do not mix Raw Type with Parametrized type. Don't use Raw Type at all.

Modify getUsers() method because you are always creating a new JsonResponse i.e you don't need to pass any object.

private JsonResponse<List<User>> getUsers(){
    JsonResponse<List<User>> jsonResponse = new JsonResponse<List<User>>();

    // Lets say I have a class called User
    List<User> users = new ArrayList<Users>();
    // get users and add to list

    jsonResponse.setResponseData(users); // No warning on this line
    jsonResponse.setSuccess(true);
    return jsonResponse;
}

Please confirm. Most probably you have defined it as

public void setResponseData(Object value){...}

Replace it with below one

public void setResponseData(T value){...}
Braj
  • 46,415
  • 5
  • 60
  • 76