0

I'm trying to pass a method as parameter. How to do it?

I have this in mind:

private static final Logger LOGGER = LoggerFactory.getLogger(MyClass.class);

@ExceptionHandler({ MyClass.class })
public ResponseEntity<BaseResponse> handleSLException(ServiceLayerException e, WebRequest request) { 

    checkCookie(request);
    } 
public void checkCookie(WebRequest request) {
     String answer = request.getHeader("cookie");
     if(answer!=null) {
        LOGGER.error("The cookies are: " + answer);
                }

How can I do the same thing using Java 8 with Lambda? I would like to be able to use the same method with more advanced technology.

1 Answers1

0

I believe the below code describes what you are looking for. You can use a predicate or similar expression to achieve what you require. import java.util.function.Predicate;

public class  Snippet{  

    private static Predicate pred = (element) -> element.equals("Sample3");
    private static Predicate pred2 = (element) -> element.equals("Sample3");
         public static void main(String args[]){String[] strArray = {"Sample3", "Sample4", "Sample5"};

         for(String str: strArray) {
             System.out.print("pred1");
             test(pred,str);
             System.out.print("pred2");
             test(pred2,str);
         }

         }

         public static void test(Predicate p,String str) {
             System.out.println(p.test(str));
         }
    }
akshaya pandey
  • 997
  • 6
  • 16
  • How would you do it in my case? –  Dec 19 '17 at 14:28
  • You should create different predicates for each scenario you have.Then based on the type of cookie, you should pass the correct predicate as a parameter to you checkCookie() method along with the cookie. – akshaya pandey Dec 19 '17 at 14:39