-
Enhancement
-
Resolution: Duplicate
-
P5
-
None
-
1.2.0, 1.4.2, 6
-
generic, x86
-
generic, windows_xp
Name: jl125535 Date: 06/10/2004
A DESCRIPTION OF THE REQUEST :
Functors are a powerful part of languages like C++ that allow for generic algorithms and callbacks. Unfortunately, it is more work to create them in Java than to use workarounds like (anonymous) inner classes.
Reflection could be used to create functors, but is unwieldy and error-prone to use in everyday coding, mostly due to security checks, type safety issues, and a lack of compile-time checks.
Ideally, a Java functor would be just as safe and easy to use as an instance of an interface but free from class proliferation.
One possibility is to add a '#' separator that is quite similar to the '.' separator for method calls. Rather than calling the method, however, the expression would return a functor that encapsulates the java.lang.reflect.Method and target object (if any). The functor's invoke() method could be used to call the method without a need for security checks or for exposing the target/Method details.
JUSTIFICATION :
Many interfaces in Java (most event listeners, Comparator, etc) are only necessary to provide decoupled, generic callback and algorithm support. If the language supported functors directly, class proliferation could be greatly reduced, and code would be more readable and maintainable.
Using generics, reflection, and an enhanced compiler, it would be possible to encapsulate a method call into an Object that could then be passed around easily.
- compile-time type safety
- subject to compile-time accessibility checks rather than runtime security checks
- simple syntax
EXPECTED VERSUS ACTUAL BEHAVIOR :
EXPECTED -
// need a comparator?
BinaryFunction<Integer, Float, Float> comp = Float#compare(float, float); // static method
BinaryFunction<Integer, Foo, Foo> comp = this#customFooCompare(Foo, Foo); // private method ('this' keyword optional)
// how about an ActionListener?
UnaryProcedure<ActionEvent> l = this#printButtonPressed(ActionEvent);
ACTUAL -
// comparator
Comparator comp = new Comparator() {
public int compare(Object a, Object b) {
return customFooCompare((Foo) a, (Foo) b);
}
};
// ActionListener
ActionListener l = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
printButtonPressed(evt);
}
};
CUSTOMER SUBMITTED WORKAROUND :
Write an inner class (bulky) or use reflection (dangerous).
(Incident Review ID: 276947)
======================================================================
- duplicates
-
JDK-6487635 Compiler support for methods as method parameters
-
- Closed
-
-
JDK-5014235 Closures support instead of anonymous inner classes
-
- Closed
-
- relates to
-
JDK-6500704 Add language support for converting methods to interfaces
-
- Closed
-