Is it possible to create a method that returns a method in Java?
up vote
1
down vote
favorite
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).
java
add a comment |
up vote
1
down vote
favorite
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).
java
It would be easier to understand what you want to achieve and provide a good answer if you posted code. You probably want to return a Function<Xxx> or a Predicate<Xxx>:return this::isField1Valid
– JB Nizet
Nov 21 at 16:59
in any case do not deal with exceptions: first, you should throw a specific type of Exception. Not Exception. But anyway, just define your own functional interface which has a single method accepting a String (or a generic type?) and throws an exception. Then you can use a method reference or a lambda to create an instance of that functional interface.
– JB Nizet
Nov 21 at 17:38
add a comment |
up vote
1
down vote
favorite
up vote
1
down vote
favorite
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).
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).
java
java
edited Nov 21 at 18:08
asked Nov 21 at 16:53
Ooalkman
83
83
It would be easier to understand what you want to achieve and provide a good answer if you posted code. You probably want to return a Function<Xxx> or a Predicate<Xxx>:return this::isField1Valid
– JB Nizet
Nov 21 at 16:59
in any case do not deal with exceptions: first, you should throw a specific type of Exception. Not Exception. But anyway, just define your own functional interface which has a single method accepting a String (or a generic type?) and throws an exception. Then you can use a method reference or a lambda to create an instance of that functional interface.
– JB Nizet
Nov 21 at 17:38
add a comment |
It would be easier to understand what you want to achieve and provide a good answer if you posted code. You probably want to return a Function<Xxx> or a Predicate<Xxx>:return this::isField1Valid
– JB Nizet
Nov 21 at 16:59
in any case do not deal with exceptions: first, you should throw a specific type of Exception. Not Exception. But anyway, just define your own functional interface which has a single method accepting a String (or a generic type?) and throws an exception. Then you can use a method reference or a lambda to create an instance of that functional interface.
– JB Nizet
Nov 21 at 17:38
It would be easier to understand what you want to achieve and provide a good answer if you posted code. You probably want to return a Function<Xxx> or a Predicate<Xxx>:
return this::isField1Valid
– JB Nizet
Nov 21 at 16:59
It would be easier to understand what you want to achieve and provide a good answer if you posted code. You probably want to return a Function<Xxx> or a Predicate<Xxx>:
return this::isField1Valid
– JB Nizet
Nov 21 at 16:59
in any case do not deal with exceptions: first, you should throw a specific type of Exception. Not Exception. But anyway, just define your own functional interface which has a single method accepting a String (or a generic type?) and throws an exception. Then you can use a method reference or a lambda to create an instance of that functional interface.
– JB Nizet
Nov 21 at 17:38
in any case do not deal with exceptions: first, you should throw a specific type of Exception. Not Exception. But anyway, just define your own functional interface which has a single method accepting a String (or a generic type?) and throws an exception. Then you can use a method reference or a lambda to create an instance of that functional interface.
– JB Nizet
Nov 21 at 17:38
add a comment |
2 Answers
2
active
oldest
votes
up vote
0
down vote
accepted
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.
1
It was reflection I needed, thank you so much !
– Ooalkman
Nov 21 at 19:20
You are welcome bro
– Omar Ahmed
Nov 23 at 13:30
add a comment |
up vote
2
down vote
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);
add a comment |
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
up vote
0
down vote
accepted
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.
1
It was reflection I needed, thank you so much !
– Ooalkman
Nov 21 at 19:20
You are welcome bro
– Omar Ahmed
Nov 23 at 13:30
add a comment |
up vote
0
down vote
accepted
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.
1
It was reflection I needed, thank you so much !
– Ooalkman
Nov 21 at 19:20
You are welcome bro
– Omar Ahmed
Nov 23 at 13:30
add a comment |
up vote
0
down vote
accepted
up vote
0
down vote
accepted
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.
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.
answered Nov 21 at 18:17
Omar Ahmed
105
105
1
It was reflection I needed, thank you so much !
– Ooalkman
Nov 21 at 19:20
You are welcome bro
– Omar Ahmed
Nov 23 at 13:30
add a comment |
1
It was reflection I needed, thank you so much !
– Ooalkman
Nov 21 at 19:20
You are welcome bro
– Omar Ahmed
Nov 23 at 13:30
1
1
It was reflection I needed, thank you so much !
– Ooalkman
Nov 21 at 19:20
It was reflection I needed, thank you so much !
– Ooalkman
Nov 21 at 19:20
You are welcome bro
– Omar Ahmed
Nov 23 at 13:30
You are welcome bro
– Omar Ahmed
Nov 23 at 13:30
add a comment |
up vote
2
down vote
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);
add a comment |
up vote
2
down vote
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);
add a comment |
up vote
2
down vote
up vote
2
down vote
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);
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);
answered Nov 21 at 17:09
Andreas
74.3k457118
74.3k457118
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53417004%2fis-it-possible-to-create-a-method-that-returns-a-method-in-java%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
It would be easier to understand what you want to achieve and provide a good answer if you posted code. You probably want to return a Function<Xxx> or a Predicate<Xxx>:
return this::isField1Valid
– JB Nizet
Nov 21 at 16:59
in any case do not deal with exceptions: first, you should throw a specific type of Exception. Not Exception. But anyway, just define your own functional interface which has a single method accepting a String (or a generic type?) and throws an exception. Then you can use a method reference or a lambda to create an instance of that functional interface.
– JB Nizet
Nov 21 at 17:38