Java – Does reflection in Java make its functions “first class”

functional programmingjava

I am always hearing people talk about how Java does not support first class functions, that it is an advantage you get from functional languages, the only way to simulate it in Java is through the use of anonymous inner classes etc..

However, from what I can see Java does support first functions through the use of its reflection API. For example I can create a method object from a class and then call it on a number of objects of that class. I realize it is not as powerful as first class functions in other languages. For example in Python you can do the following:

class Test:
    def __init__(self, num):
        self.number = num
    def add(self, num):
        self.number += num
test = Test(1)
method = test.add
method(2)

You cannot do this in Java because you need to have a reference to the object you want to invoke the method on. However you can still treat the method as an object which is what defines first class functions. I guess the method object is not really the actual function but rather a meta-data object, although using reflection it can be treated as such. Maybe I just need clarification on what defines a first class function.

Best Answer

A first class function is one where the function is available on its own. C, C++, and Ruby allow this approach. Java requires the function to be tied to a class and only provides a metadata representation of it, even if that class is merely a static collection of functions. C# supports first class functions with lambdas (which are based off of lambda calculus) and delegates.

Ruby is one of the languages that truly supports first class functions. The difference is that not only can you define functions on their own, but you can pass them as arguments and invoke methods on them. Check out Ruby's Proc object which is used to represent an arbitrary block of code.

The end result of having first class functions is the fact that it lends to some very powerful and flexible coding constructs. This is distinctly different than hacking around first class functions using the reflection API.

Java doesn't have full support of first class functions. The reflection API can give you some semblance of first class functions if the Method object is referencing a static method. In essence you can invoke a static method like this:

Method reference = mathClass.getMethod("sqrt");

// NOTE: the first parameter is for the object instance,
// but for static methods it is ignored
double answer = (double)reference.invoke(null, 4);

As soon as you are working with an instance method, you lose that first class function ability. You might be able to hack together some reflection based delegate support similar to C#, but the resulting code will be much slower. The "delegate" would take care of keeping the object reference for future invocations.