Is it possible to create a method that returns a method in Java?
up vote
0
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
New contributor
Ooalkman is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
add a comment |
up vote
0
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
New contributor
Ooalkman is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
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
yesterday
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
yesterday
add a comment |
up vote
0
down vote
favorite
up vote
0
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
New contributor
Ooalkman is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
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
New contributor
Ooalkman is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
New contributor
Ooalkman is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
edited yesterday
New contributor
Ooalkman is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
asked yesterday
Ooalkman
32
32
New contributor
Ooalkman is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
New contributor
Ooalkman is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
Ooalkman is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
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
yesterday
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
yesterday
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
yesterday
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
yesterday
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
yesterday
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
yesterday
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
yesterday
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
yesterday
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.
It was reflection I needed, thank you so much !
– Ooalkman
yesterday
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.
It was reflection I needed, thank you so much !
– Ooalkman
yesterday
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.
It was reflection I needed, thank you so much !
– Ooalkman
yesterday
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 yesterday
Omar Ahmed
163
163
It was reflection I needed, thank you so much !
– Ooalkman
yesterday
add a comment |
It was reflection I needed, thank you so much !
– Ooalkman
yesterday
It was reflection I needed, thank you so much !
– Ooalkman
yesterday
It was reflection I needed, thank you so much !
– Ooalkman
yesterday
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 yesterday
Andreas
73.3k456118
73.3k456118
add a comment |
add a comment |
Ooalkman is a new contributor. Be nice, and check out our Code of Conduct.
Ooalkman is a new contributor. Be nice, and check out our Code of Conduct.
Ooalkman is a new contributor. Be nice, and check out our Code of Conduct.
Ooalkman is a new contributor. Be nice, and check out our Code of Conduct.
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
yesterday
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
yesterday