Reputation: 2947
Ok, I know this is been asked and answered hundreds of times, and I know I'm probably going to get the "go search for the answer" response, but I'm going to try asking anyway. Very simply, I want to pass a method and use it to do the writing of a string. For example:
void writeStuff(Method method) {
method.invoke("the string to write");
}
This way, I could hand it the method that would be receiving the string, such as System.out.print, or LOGGER.info. Heck, why not any method that accepts a String as an
Upvotes: 0
Views: 63
Reputation: 109613
For a non-static method you need its object, otherwise this owner can be null. And then there are the exceptions to handle.
void writeStuff(Object owner, Method method) {
method.invoke(owner, "the string to write");
}
Therefore till a next version of java, one uses an interface (with one method) and passes instances of these:
interface Printable { void print(String s); }
void writeStuff(Printable p) {
p.print("...");
});
writeStuff(new Printable() {
@Override public void print(String s) { System.out.println(s); }
});
For a static method, a function, one indeed needs no this
(owner).
In a top ultimate language like Algol68 (1968 but still active!) one could do:
REAL y = IF c THEN sin ELSE cos FI (x);
were sin and cos are names for code values having type PROC(REAL)REAL.
Java make a sad distinction between field and method: you can have a field int x
and method void x(boolean)
with the same name, overloaded methods boolean x()
. For something like function objects one never could use System.out.println
.
Upvotes: 1
Reputation: 1290
You have to specify the object on which the method should be called, too.
Indeed, you can read this from popular sources:
and
Sun/Oracle tutorial on invoking methods
--tb
Upvotes: 0
Reputation: 870
Did you read the documentation for invoke?
http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/reflect/Method.html#invoke(java.lang.Object, java.lang.Object[])
Upvotes: 0