Ooalkman
Ooalkman

Reputation: 3

Is it possible to create a method that returns a method in Java?

I'd like to know if in Java, it is possible to create a method that returns a method : when treating a form, I need to check for each field that the user filled it with the correct pattern. This checking is different for every field so I created a different method for every field, and now I would like to code a method that can "reroute" me (i.e tell me what validation method I need to use) according to the field I'm checking.

I was wondering if I could do it by using, for instance, functions ?

EDIT (sorry for not posting that in the first place) : To be more specific, the complication here is that the methods won't return anything but are rather used to generate exceptions if the field is not validated. For instance :

private void emailValidation(String email) throws Exception {
    if (email != null) {
        if (!email.matches("([^.@]+)(\\.[^.@]+)*@([^.@]+\\.)+([^.@]+)")) {
            throw new Exception("The e-mail is not valid.");
        }
    } else {
        throw new Exception("Please write an e-mail address.");
    }
}

So yeah, I know I can use functions but all the examples I see are quite simple or in any case do not deal with exceptions and I do not know how I can use those in that case.

EDIT : Should I do something like that ?

private Consumer<String> validation(Field field) throws Exception {
    try {
        switch (field) {
        case Name:
            return value -> nameValidation(value);
            break;
        case Email:
            return value -> emailValidation(value);
            break;
        case Password:
            return value -> passwordValidation(value);
            break;          
        }
    } catch (Exception e) {
        throw new Exception(e.getMessage());
    }
}

I really do not see the point in using functional interfaces here (because I clearly don't understand it), I could do something similar without it.

The exception thing is probably not the best thing to do but it is part of the constraints of the exercise. In fact I personally (as a noob I guess) find it quite elegant since it IS an error that we are throwing, and the convenient part is that it allows to know that there was an error while getting info about it (well, it's an object that handles errors).

Upvotes: 0

Views: 612

Answers (2)

user8188748
user8188748

Reputation:

You might mean that you want to return from a method. In this case, you can simply indicate the method is finished:

return;

If the return type is not void, you must return something:

return "some string";

or

return myObject;

Lambdas

However, you might mean that you actually want to return a function; eg. you want to return a lambda. Java, desipte the recent additions to the language in Java 8, still does not truly have first-class functions. You might consider returning an instance of the Function type:

Function<String, String> getSomeFunction() {
    return (paramOfTheFunction) -> "This is a function with param: " + paramOfTheFunction;
}

In the generics ("<>"), the first string is the input type, and the second is the output type. Then you can invoke it like this:

void myMethod() {
    Function<String, String> myFunc = getSomeFunction();
    string output = myFunc.apply("foo");  // Outputs "This is a function with param: foo"
    System.out.println(output);
}

Reflection

However, there is also a third case: you might want to actually return a method (similar to a function pointer in C++). This is possible with reflection.

void methodA() {
    System.out.println("foobar");
}
Method getMethodA() {
    // null because methodA has no parameters; this specifies parameter types
    return getClass().getMethod("methodA", null);
}

Then you can execute the returned Method using its invoke method:

getMethodA().invoke(this);

Invoke requires an instance of the class of which it is a member as the first parameter. Other parameters optionally supply arguments.

Then you can execute the returned Method using its invoke method:

getMethodA().invoke(this);

Invoke requires an instance of the class of which it is a member as the first parameter. Other parameters optionally supply arguments.

Upvotes: 0

Andreas
Andreas

Reputation: 159086

Yes, it is possible to create a method that returns a method.

That is what functional interfaces, lambdas, and method references, introduced in Java 8, is all about, i.e. treating a method as an object that can be passed around.

Lets say you need a method for validating an int value, i.e. you need a method like boolean isValid(int value). For that, you can use the built-in IntPredicate functional interface.

public static IntPredicate getAgeValidator() {
    return i -> i >= 21;
}

That method returns a method that validates that the age (an int value) is at least 21.

The returned "validation method" can then be used like this:

int age = 25;
boolean valid = getAgeValidator().test(age);

Upvotes: 2

Related Questions