Joe
Joe

Reputation: 4514

A reference to a method in java

I've been playing around with functional programing a little recently and I suspect it's got to me. But there's something I'd like to be able to do in Java and I'm not sure if It can be done.

I have an object 'ob' of type 'A'. I also have a library of methdods (several thousand, automatically generated ones-that take the same arguments) that I might want to a attach to ob. What I'd like to be able to write is

A ob = new A(Someint, someint, Method mymethod);

And then be able to write (within A) something along the lines of)

X = mymethod.call(arg1, arg2);

Is there something in Java that let's me do this? Or have I stayed too far from the light?

Upvotes: 2

Views: 73

Answers (3)

Java42
Java42

Reputation: 7706

Passing a Method reference to a method and then invoking the method with parameters.

There are various flavors on ways to do this. This instructional example uses a static method named myMethod taking one Object as a parameter.

import java.lang.reflect.Method;

public class Tester54 {

    static public class J42 {
        static public Object myMethod(final Object o) {
            return "Wow:" + o.toString();
        }
    }

    private static void 
    doIt(final Class<?> c, final Method m, final Class<?>[] types, final Object[] args) 
        throws Exception {
        final Object s = m.invoke(J42.class, new Object[] { "wow" });
        System.out.println(s);
    }

    public static void main(final String[] a) throws Exception {
        final Method m = J42.class.getMethod("myMethod", new Class<?>[] { Object.class });
        final Class<?>[] types = new Class[] { Object.class };
        final Object[] args = new Object[] { "wow" };
       doIt(J42.class, m, types, args);
    }

}

Upvotes: 0

Svante
Svante

Reputation: 51501

You can't do exactly that in Java. As a workaround, you can use an anonymous inner class.

Define an interface:

interface Func <A, B> {
    A run (B arg);
}

Instantiate it on the fly to create a "function object":

C ob = frobn (someint,
              new Func <int, long> () {
                  @Override
                  int run (long arg) {
                       // do something to return that int
                  }
              });

You then call the passed Func inside frobn like this:

C frobn (int some, Func <int, long> fun) {
    // do something
    int foo = fun.run (bar);
    // do something
}

Yes, that is ugly greenspunning.

Upvotes: 1

Peter Lawrey
Peter Lawrey

Reputation: 533472

What you really need is Java 8 with lambda support. Anything else will be really ugly. (Even with this Java has functional support but nothing like a true functional language) I suggest you try

http://jdk8.java.net/lambda/

With this you can write lambdas line p -> p.getPrice() and function references like MyClass::myMethod

http://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html

Upvotes: 1

Related Questions