简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM