Is there a way to statically reference a method for reflection in Java. Here’s some example code to give you an idea of what I am attempting:
public void myFunc(int x) { ... }
public void other() {
Method m1 = getClass().getMethod("myFunc"); // dynamic
Method m2 = this.myFunc; // static
Method m3 = MyClass.myFunc; // static (alternate)
}
I recognize that the above syntax does not work, but I was wondering if there is some sort of syntax similar to this that actually does work. I want a way to use reflection without worrying about the inherent dangers of referencing a method by a string.
Is there a way to do this, or is it just a pipe-dream?
Method references explains
and it goes on to explain the various kinds of method references:
HISTORICAL NOTE (Written before Java 8 was finalized)
I think the Java closures proposal has something like this. Stephen Colebourne says:
but I don’t think this syntax is available in any shipping JVM. Closures themselves are definitely not in Java 7. You might see it in Java 8.
The Java closures site has a pointer to “Method references” which is a bit more up-to-date though it doesn’t look like they’ve changed the syntax much.