fvdalcin
fvdalcin

Reputation: 1047

Weird exception while using contains() method

I'm building a web application using Spring MVC framework.

I have some controller which adds some attributes (users belonging to the same team) to my view, as follows:

@RequestMapping(value = "/friends", method = RequestMethod.GET)
    public ModelAndView showFriends(Principal principal) {
       ModelAndView mav = new ModelAndView("friends");

       User currentUser = userService.findUser(principal.getName());

       // this method returns a Collection<long> of userIds from users that belong to a given team
       Collection<long> userIds = findUsersFromTeam(currentUser.getTeam());

       mav.addObject("users", userIds);
       mav.addObject("currentUser", userService.findUsers();
       return mav;
    }

And, in my "friends.jsp" file, I do the following test:

<c:when test="${users.contains(currentUser.id)}">

Which throws the following exception:

java.lang.NoSuchMethodException: java.util.ArrayList.contains(java.lang.Long)

However, ArrayList class implements contains(Object o) method. What's wrong?

Upvotes: 0

Views: 133

Answers (1)

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 280132

This is a just a result of how EL parses method expressions and how reflection works

${users.contains(currentUser.id)}

It gets the type of users, ArrayList, and the type of currentUser.id, Long. It then uses reflection to get a method named contains with a parameter of type Long on the type ArrayList. It doesn't find one because one doesn't exist. Remember, reflection does not apply inheritance hierarchy checking on parameter list elements.

So even though there is a ArrayList#contains(Object), there is no ArrayList#contains(Long). It therefore fails.

Don't use basic EL for this. Write your own EL function or do the logic in your handler method.

Upvotes: 4

Related Questions