Re: Can a method be a parameter of another method in Java?
Shawn wrote:
Ingo R. Homann wrote:
Of course it can, see below. A great advantage of Java is, that its
solution is also typesafe!
Ciao,
Ingo
interface Mapper {
int map(int d);
}
class Test {
double sum(Mapper m, int a, int b) {
...
}
Fantastic! Thank you very much. I didn't realize interface can be such a
use--place holder. I thought interface was only used in inheritance.
Don't overlook the use of Interface in conjunction with other forms of
inheritance at the same time:
class hickey extends dohickey implements blah, Mapper {
....
}
Now a class that does a lot of things (like things you need for your
design) can also be used for a Mapper object. This particular pattern
happens a lot in Swing, for example, especially for action listeners, so
be on the look out for it.
Also, there is another way of doing what you ask. The Method object
corresponds much more closely to a C function pointer:
class myInvoker( Method func_ptr )
{
funct_ptr.invoke();
}
static main (args[])
{
Object o = new Integer();
Class[] parameterTypes = new Class[] {String.class};
Method m = = c.getMethod("concat", parameterTypes);
myInvoker( m );
}
Except that there's a lot more needed than that (I omitted big try ...
catch blocks, for starters). However, the Method object can be used to
sling methods around something like C functions.
What this is useful for is when you can't use Interfaces. For example,
you are passed an Object, and you'd like to be able to access methods by
name. A method called "getName" which returns a string, and a method
called "setName(String)" could be used to set a property called Name in
the Object, and there's no need for any Interface or inheritance at all.
This provides a lot of flexibility for your programs.
You can also look at an Object, and find what Interfaces it implements,
and even pick and choose which Interfaces you want. For example, you
might want Mapper2_0, but you'll settle for Mapper1_0. Again, lots of
flexibility for your programs.
The whole subject is called Reflection, for more go to:
Finding Interface:
http://java.sun.com/docs/books/tutorial/reflect/class/getInterfaces.html
Invoking methods, the real example:
http://java.sun.com/docs/books/tutorial/reflect/object/invoke.html
More reflection, the whole she-bang:
http://java.sun.com/docs/books/tutorial/reflect/index.html