Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In java can i store a method in a variable? [duplicate]

Tags:

java

methods

Possible Duplicate:
Java - Creating an array of methods

In java can i store a method in a variable? For example can i have an array of methods? If so how would i do this?

like image 995
David Avatar asked May 09 '11 06:05

David


4 Answers

In Java 6 and below, you'd need to use reflection (see the java.lang.reflect package). Java 7 is meant to have some new features in this regard (specifically method handles (JSR 292) and the new "invoke dynamic" stuff). Java 8 (some way off, then) looks set to have lambda expressions (and yes, that link is to an OpenJDK page, but they say Oracle's on board), which aren't quite the same thing, but are related.

like image 102
T.J. Crowder Avatar answered Dec 03 '22 10:12

T.J. Crowder


I will recommend you to hold the output in a variable rather than calling the function again. Because the variable is going to be held in memory as long as it requires. After that automatic garbage collection will take care of that to free it up from the memory. But if you put method in variable that will eat up the memory for its activation record stack each time it gets called. So its good practice to store output in variable instead of method.

like image 26
Rupeshit Avatar answered Dec 03 '22 08:12

Rupeshit


Yeah you can do that. You have the Method class.

like image 25
rkg Avatar answered Dec 03 '22 08:12

rkg


It is possible if you use reflection and the Method data type.

like image 26
Nico Huysamen Avatar answered Dec 03 '22 10:12

Nico Huysamen