Purpose of Functional Interfaces in Java8 - java

I've come across many questions in regards of Java8 in-built Functional Interfaces, including this, this, this and this. But all ask about "why only one method?" or "why do I get a compilation error if I do X with my functional interface" and alike. My question is: what is the existential purpose of these new Functional Interfaces, when I can use lambdas anyway in my own interfaces?
Consider the following example code from oracle documentation:
// Approach 6: print using a predicate
public static void printPersonsWithPredicate(List<Person> roster,
Predicate<Person> tester) {
for (Person p : roster) {
if (tester.test(p)) {
System.out.println(p);
}
}
}
OK, great, but this is achievable with their own example just above (an interface with a single method is nothing new):
// Approach 5:
public static void printPersons(<Person> roster,
CheckPerson tester) {
for (Person p : roster) {
if (tester.test(p)) {
System.out.println(p);
}
}
}
interface CheckPerson {
boolean test(Person p);
}
I can pass a lambda to both methods.
1st approach saves me one custom interface. Is this it?
Or are these standard functional interfaces (Consumer, Supplier, Predicate, Function) are meant to serve as a template for code organization, readability, structure, [other]?

Obviously you can skip using these new interfaces and roll your own with better names. There are some considerations though:
You will not be able to use custom interface in some other JDK API unless your custom interface extends one of built-ins.
If you always roll with your own, at some point you will come across a case where you can't think of a good name. For example, I'd argue that CheckPerson isn't really a good name for its purpose, although that's subjective.
Most builtin interfaces also define some other API. For example, Predicate defines or(Predicate), and(Predicate) and negate().
Function defines andThen(Function) and compose(Function), etc.
It's not particularly exciting, until it is: using methods other than abstract ones on functions allows for easier composition, strategy selections and many more, such as (using style suggested in this article):
Before:
class PersonPredicate {
public Predicate<Person> isAdultMale() {
return p ->
p.getAge() > ADULT
&& p.getSex() == SexEnum.MALE;
}
}
Might just become this, which is more reusable in the end:
class PersonPredicate {
public Predicate<Person> isAdultMale() {
return isAdult().and(isMale());
}
publci Predicate<Person> isAdultFemale() {
return isAdult().and(isFemale());
}
public Predicate<Person> isAdult() {
return p -> p.getAge() > ADULT;
}
public Predicate<Person> isMale() {
return isSex(SexEnum.MALE);
}
public Predicate<Person> isFemale() {
return isSex(SexEnum.FEMALE);
}
public Predicate<Person> isSex(SexEnum sex) {
return p -> p.getSex() == sex;
}
}

Although you ask "Is that it?", it's very nice that we don't have to write a new interface ever time we want type for a lambda.
Ask yourself, if you're reading an API, which is easier for a programmer to use:
public void processUsers(UserProcessor userProcessor);
... or ...
public void processUsers(Consumer<User> userProcessor);
With the former, I have to go and take a look at UserProcessor to find out what one is, and how I could create one; I don't even know it could be implemented as a lambda until I go and find out. With the latter, I know immediately that I can type u -> System.out.println(u) and I'll be processing users by writing them to stdout.
Also the author of the library didn't need to bloat their library with Yet Another Type.
In addition, if I coerce a lambda to a Functional Type, I can use that type's composition methods, for example:
candidates.filter( personPredicates.IS_GRADUATE.negate());
That gives you Predicate methods and(), or(), negate(); Function methods compose(), andThen() -- which your custom type would not have unless you implemented them.

Java API provides many built-in Function Interfaces for java developers. and we can use the built-in Function Interfaces many times. but there two reasons to use a Customer Function Interface.
Use a Customer Function Interface to describe explicitly what's like.
let's say you having a class User with a name parameter on the constructor.when you use the built-in Function Interface to refer the constructor the code like below:
Function<String,User> userFactory=User::new;
if you want describe it clearly you can introduce your own Function Interface, e.g:UserFactory;
UserFactory userFactory=User::new;
another reason to use Custom Function Interface due to built-in Function Interface is confused in somewhere. when you see a parameter with type Function<String,User>,is it create a new user or query an user from database or remove the user by a string and return the user,...?if you use an exactly Function Interface you know what it doing,as an UserFactory is create an user from a string username.
Use a Customer Function Interface to processing checked Exception in java built-in Function Interface.
Due to the built-in Function Interface can't be throwing a checked Exception,the problem occurs when you processing something in lambda expression that may be throws a checked exception,but you don't want to use the try/catch to handle the checked Exception,which will be tends to many code difficult to read in lambda expression.then you can define your own Function Interface that throws any CheckedException and adapt it to the built-in Function Interface when using java API.the code like as below:
//if the bars function throws a checked Exception,you must catch the exception
Stream.of(foos).map(t->{
try{
return bars.apply(t);
}catch(ex){//handle exception}
});
you also can define your own Function Interface throws a checked Exception,then adapt it to built-in Function,let's say it is a Mapping interface,the code below:
interface Mapping<T,R> {
R apply(T value) throws Exception;
}
private Function<T,R> reportsErrorWhenMappingFailed(Mapping<T,R> mapping){
return (it)->{
try{
return mapping.apply(it);
}catch(ex){
handleException(ex);
return null;
}
};
}
Stream.of(foos).map(reportsErrorWhenMappingFailed(bars));

Related

When is dynamic polymorphism necessary (compared with static polymorphism)?

I come from functional languages (e.g. Haskell) and I enjoy a lot on typeclasses to achieve polymorphism which is also a structural approach to implement ad-hoc overloading.
However, recently I'm starting to understand OOP's way to model real problems and I'm curious why do we need dynamic polymorphism in OOP languages (such as Java). In my experience, most of function call can be resolved during compile time as many functional languages do not support subtyping.
So my problem is that, In what kind of situation do we have to use dynamic polymorphism instead of compile-time polymorphism? My guesses are:
When we use the subtype system where we have objects we cannot decide its actual type (e.g. we have a container containing many objects of various types. However, in this situation, why not try Algebraic data type or union type to model the container's element type?).
We only have the object and we do not know its methods' real name, so we have to use the vptr table to help us.
In Haskell, we replace "dynamic polymorphism" with higher-order functions.
Consider the following problem: we want to define a type which denotes a predicate. We will eventually use this type Predicate when we implement our Lists so that we can define the filter function. We would like to be able to easily define the equality predicate, the less-than predicate, and be able to combine two predicates by joining them with "and".
A reasonable Java attempt would look like this.
interface Predicate<T> {
public abstract boolean predicate(T x);
}
class EqualsPredicate<T> implements Predicate<T> {
private final T value;
public EqualsPredicate(T value) {
this.value = value;
}
#Override
public boolean predicate(T x) {
return this.value.equals(x);
}
}
class LessPredicate<T implements Comparable<T>> implements Predicate<T>{
private final T value;
public LessPredicate(T value) {
this.value = value;
}
#Override
public boolean predicate(T x) {
return this.value.compareTo(x) < 0;
}
}
class AndPredicate<T> implements Predicate<T> {
private final Predicate<T> p1;
private final Predicate<T> p2;
public AndPredicate(Predicate<T> p1, Predicate<T> p2) {
this.p1 = p1;
this.p2 = p2;
}
#Override
public boolean predicate(T x) {
return p1.predicate(x) && p2.predicate(x);
}
}
In Haskell, the answer to this conundrum is obvious. We just define
type Predicate t = t -> Bool
makeEqualsPredicate :: Eq t => t -> Predicate t
makeEqualsPredicate = (==)
makeLessPredicate :: Ord t => t -> Predicate t
makeLessPredicate = (<)
makeAndPredicate :: Predicate t -> Predicate t -> Predicate t
makeAndPredicate p1 p2 x = p1 x && p2 x
-- or, even more succinctly, makeAndPredicate = liftA2 (&&)
Java allows "dynamic dispatch" of methods through subclassing. Haskell allows "dynamic dispatch" of functions through higher-order functions.
But wait, you say. Predicate was an interface with only one method. What should we do if we want to have two methods?
Well, if an interface with one method corresponds to a function, an interface with two methods must correspond to a pair of functions. This is just the OOP principle known as "composition over inheritance".
So we can always replace Java-style dynamic polymorphism with Haskell-style higher-order functions.
In fact, you actually see this observation in modern Java as well. As of Java 8, you can add the annotation #FunctionalInterface to an interface with one method, which permits you to create instances of that interface using lambdas. So you could write in Java 8
#FunctionalInterface
interface Predicate<T> {
public abstract boolean predicate(T x);
public static Predicate<J> makeEqualsPredicate(J t) {
return (x) -> t.equals(x);
}
public static Predicate<J implements Comparable<J>> makeLessPredicate(J t) {
return (x) -> t.compareTo(x) < 0;
}
public Predicate<T> makeAndPredicate(Predicate<T> other) {
return (x) -> this.predicate(x) && other.predicate(x);
}
}
With many people's help, currently I've got some of answers I want after reflecting lots of designs. Since Rust has both nice support for static and dynamic polymorphism, I shall use Rust in this answer to demonstrate my points.
I now have 2 points for dynamic dispatch: user-friendly scalability and smaller compiled size .
Point 1: user-friendly scalability
Many people argue that dynamic dispatch is suitable for a situation where you have a container to collect various kinds of objects(of course, different types). For example:
trait MyTrait {
fn method(&self, ...) -> ReturnType;
}
type MyContainer = Vec<Box<MyTrait>>;
fn main() {
...
//the_container : MyContainer
the_container.iter().map(... { x.method(...) } ...) //only demo code
}
In code above, on compile time, we only know that the elements are trait objects, which means the program shall use a vptr-like strategy to find which method to use during executing the expression in the main function.
However, there's another way to implement nearly the same thing:
enum MyContainerTypes {
Type0 A,
Type1 B,
...
}
impl MyTrait for MyContainerType {
fn method(&self, ...) -> ReturnType {
match self {
Type0 a => {...},
Type1 b => {...},
...
}
}
}
type MyContainer = Vec<MyContainerType>;
fn main() {
...
//my_container : MyContainer
my_container.iter().map(... { x.method(...) } ...); //demo
}
In this way, no dynamic polymorphism is required, however, consider the following situation: You are a user of a library which has been designed and you have no access to change definitions like enums inside the library. Now you want to make your own type of ContainerType and you want to reuse codes of existed logic. If you are using dynamic dispatch, the work is simple: just make another impl of your custom container type and everything's fine. Unfortunately, if you are using the static version of the library, it may become a little hard to achieve this goal...
Point 2: Smaller compiled size
Languages like Rust may have to compile a generic function many times, once for each type it’s used with. This could make the binary large, a phenomenon called code bloat in C++ circles.
Let's consider a simpler case:
trait MyTrait {
fn method(&self, ...) -> ReturnType;
}
fn f(x: MyTrait) { ... } //MyTrait is unsized, this is unvalid rust code
fn g<T: MyTrait>(x: T) { ... }
If you have lots of functions like function g, the compiled size may become larger and larger. However this should not be a big issue since most of us have the luxury of ignoring code size for plentiful memory nowadays.
Conclusion
In short, although static polymorphism has many advantages over dynamic polymorphism, there're still some corners dynamic dispatch can work better. Personally I really love Haskell-like's way to treat polymorphism(that's also why I like Rust). I don't think this can be the final best and complete answer, discussions are welcome!
Combining strategies
It suddenly occurred to me that why not combine the static and dynamic strategies? To allow users to further extend our model, we can just leave a small hole for users to fill in later, like:
trait Custom {
fn method(&self) -> ReturnType;
}
enum Object {
A(Type0),
B(Type1),
...
Hole(Box<dyn Custom>)
}
However, in this way, some operations like clone may be a little hard to implement, but I think this is still an interesting idea.
Update
Haskell's existential type also has similar function and implementation as dynamic polymorphism in OOP languages:
data Obj = forall a. (Show a) => Obj a
xs :: [Obj]
xs = [Obj 1, Obj "foo", Obj 'c']
doShow :: [Obj] -> String
doShow [] = ""
doShow ((Obj x):xs) = show x ++ doShow xs
I also found that this existential type can be used to hide some details of types and provide cleaner interface for users to use.
Edit
Thanks #MarkSaving. There's a mistake in Point 2's code, the dyn trait object is unsized and therefore should be changed to a reference or boxed dyn:
fn f(x: Box<dyn MyTrait>) { ... }

Generate lambda class for generic type variable using reflection

I am attempting to use Java interfaces as mixins in some high-level wrapper for type D.
interface WrapsD {
D getWrapped();
}
interface FeatureA extends WrapsD {
default ...
}
interface FeatureB extends WrapsD {
default ...
}
abstract class DWrapperFactory<T extends WrapsD> {
protected T doWrap(D d) {
return () -> d; // <- does not work
}
}
interface FeatureAB extends FeatureA, FeatureB {
}
class ProducingDWithFeatureAB extends DWrapperFactory<FeatureAB> {
protected FeatureAB doWrap(D d) {
return () -> d; // <- has to repeat this
}
}
As seen in ProducingDWithFeatureAB, doWrap has to be implemented in each sub-class even though the body is identical. (One more example of why Java generics is really broken.)
Since I already need to create concrete classes like ProducingDWithFeatureAB for other reasons and code exists in the JRE to sythesize lambda classes, it should be possible to write doWrap only once using reflection. I want to know how it can be done.
(doWrap used to be implemented using anonymous inner classes implementing the interface, which is even more biolderplate.)
This has nothing to do with generics; your generic example is just obfuscating the real issue.
Here's the core of the issue: lambda expressions need a target type that is a functional interface, and that target type must be statically known to the compiler. Your code doesn't provide that. For example, the following code would get the same error, for the same reason:
Object o = arg -> expr;
Here, Object is not a functional interface, and lambda expressions can only be used in a context whose type is a (compatible) functional interface.
The use of generics makes it more confusing (and I think you're also confusing yourself about how generics work), but ultimately this is going to be where this bottoms out.
The first thing you have to understand, is, that a method of the form
public Function<X,Y> fun() {
return arg -> expr;
}
is desugared to the equivalent of:
public Function<X,Y> fun() {
return DeclaringClass::lambda$fun$0;
}
private static Y lambda$fun$0(X arg) {
return expr;
}
whereas the types X and Y are derived from the functional signature of your target interface. While the actual instance of the functional interface is generated at runtime, you need a materialized target method to be executed, which is generated by the compiler.
You can generate instances of different interfaces for a single target method reflectively, but it still requires that all these functional interfaces have the same functional signature, e.g. mapping from X to Y, which reduces the usefulness of a dynamic solution.
In your case, where all target interfaces indeed have the same functional signature, it is possible, but I have to emphasize that the whole software design looks questionable to me.
For implementing the dynamic generation, we have to desugar the lambda expression as described above and add the captured variable d as an additional argument to the target method. Since your specific function has no arguments, it makes the captured d the sole method argument:
protected T doWrap(D d) {
Class<T> type=getActualT();
MethodHandles.Lookup l=MethodHandles.lookup();
try
{
MethodType fType = MethodType.methodType(D.class);
MethodType tType = fType.appendParameterTypes(D.class);
return type.cast(LambdaMetafactory.metafactory(l, "getWrapped",
tType.changeReturnType(type), fType,
l.findStatic(DWrapperFactory.class, "lambda$doWrap$0", tType), fType)
.getTarget().invoke(d));
}
catch(RuntimeException|Error t) { throw t; }
catch(Throwable t) { throw new IllegalStateException(t); }
}
private static D lambda$doWrap$0(D d) {
return d;
}
You have to implement the method getActualT() which ought to return the right class object, which is possible if the actual subclass of DWrapperFactory is a proper reifiable type, as you stated. Then, the method doWrap will dynamically generate a proper instance of T, invoking the desugared lambda expression’s method with the captured value of d—all assuming that the type T is indeed a functional interface, which cannot be proven at compile time.
Note that even at runtime, the LambdaMetafactory won’t check whether the invariants hold, you might get errors thrown at a later time if T isn’t a proper functional interface (and subclass of WrapsD).
Now compare to just repeating the method
protected SubtypeOfWrapsD doWrap(D d) {
return () -> d;
}
in each reifiable type that has to exist anyway…

How to organize java 8 code with Functional interfaces

I have recently started reading about java 8 features and i am confused with what seems like a very basic thing. How to organize code in 'Functional style' ?
Whatever i do, it looks very object oriented to me.
Best to explain what i ask with an example.
#FunctionalInterface
public interface SubstringOperator {
String splitAtLastOccurence(String plainText, String delimiter);
}
Let's say that in certain class i always need exactly one specific implementation of the SubstringOperator interface. I could provide implementation in the constructor like below:
public class SomeClass {
private SubstringOperator substringOperator;
public SomeClass() {
substringOperator = (s, d) -> { return s.substring(s.lastIndexOf(d)+1);};
}
}
I could now use this implementation in any method within SomeClass like this:
//...
String valueAfterSplit = substringOperator.splitAtLastOccurence(plainText, "=");
If i now wish to add another class which reuses that specific SubstringOperator implementation, should i create another class which exposes the implementation via getters?
Am i missing something obvious, or:
functions must be contained in classes in order to reuse them ?
How is that any different than object oriented paradigm ?
Put aside Stream API and other thingies, i would like to get basic understanding about code organization in java 8 for Functional style programming.
Usually it's better to reuse existing functional interfaces instead of creating new ones. In your case the BinaryOperator<String> is what you need. And it's better to name the variables by their meaning, not by their type. Thus you may have:
public class SomeClass {
private BinaryOperator<String> splitAtLastOccurence =
(s, d) -> s.substring(s.lastIndexOf(d)+1);
}
Note that you can simplify single-statement lambda removing the return keyword and curly brackets. It can be applied like this:
String valueAfterSplit = splitAtLastOccurence.apply(plainText, "=");
Usually if your class uses the same function always, you don't need to store it in the variable. Use plain old method instead:
protected static String splitAtLastOccurence(String s, String d) {
return s.substring(s.lastIndexOf(d)+1);
}
And just call it:
String valueAfterSplit = splitAtLastOccurence(plainText, "=");
Functions are good when another class or method is parameterized by function, so it can be used with different functions. For example, you are writing some generic code which can process list of strings with additional other string:
void processList(List<String> list, String other, BinaryOperator<String> op) {
for(int i=0; i<list.size(); i++) {
list.set(i, op.apply(list.get(i), other));
}
}
Or more in java-8 style:
void processList(List<String> list, String other, BinaryOperator<String> op) {
list.replaceAll(s -> op.apply(s, other));
}
In this way you can use this method with different functions. If you already have splitAtLastOccurence static method defined as above, you can reuse it using a method reference:
processList(myList, "=", MyClass::splitAtLastOccurence);

Lazy Collection in Java

Consider a problem, in which I'm developing a tree like Collection.
One of the main functionality of my Collection is to trace all the stored items one by one and then call a given function for each item until a given criteria has been met (lazy Collection).
So the function should have the following signatures:
void Trace(function func, criteria crit)
{
item i = firstItem();
while (i != endItem())
{
i = nextItem();
func(i);
if (crit(i))
return;
}
}
in C++ function pointers can be used for func and crit.
in C#, yield keyword is exactly the solution to this problem, I believe.
How can I get the same thing in Java?
In Java, you would pass references to objects of classes that implement applicable functions, or use Commons Collections instead:
Use Predicate implementations for the crit part.
Use Closure implementations for the func part.
For example:
Closure c = new Closure() {
public void execute(Object obj) {
...
}
};
Predicate p = new Predicate() {
public boolean evaluate(Object obj) {
...
}
}
Trace(c, p);
What you're looking for here is the Strategy design pattern.
The goal of this pattern to to abstract the implementation of an algorithm into a Strategy object. Here, your algorithms are the func and crit functions that you're looking to pass in.
So, you'd have an interface called something like TraceStrategy. You'd then pass implementations of this interface in to your collection. Your code would then look something like
void Trace(TraceStrategy traceStrategy)
{
item i = firstItem();
while (i != endItem())
{
i = nextItem();
traceStrategy.func(i);
if (traceStrategy.crit(i))
return;
}
}
and
interface TraceStrategy {
public boolean crit(item i);
public void func(item i);
}
You'd probably want to make this generic, so that you weren't tied to item... but you get the idea.
Create an interface that declares the methods, and require a reference to an object implementing the interface as argument. The caller can create the object using an anonymous inner class.
You can make this trace function work just fine in Java by combining a couple of techniques:
Instead of "function pointers", your parameters func and crit should be object instances that implement a specific interface. You can then call a function in this interface on the object i. In effect, this is a Vistor Pattern with two different vistor parameters.
You also need some way to traverse the tree. You could implement an Iterator - this gives you a nice way to traverse the entire structure. Alternatively you could make trace recursive (it calls itself on left and right branches of the tree) and then you wouldn't need an iterator.
The iterator version would look something like this:
public void trace(IFunction func, ICriteria crit) {
for (T i: this) {
func.call(i);
if (crit.test(i)) return;
}
}
Here T is the item type of the collection, and call and test are the function definitions in the IFunction and ICriteria interfaces respectively.

What's the nearest substitute for a function pointer in Java?

I have a method that's about ten lines of code. I want to create more methods that do exactly the same thing, except for a small calculation that's going to change one line of code. This is a perfect application for passing in a function pointer to replace that one line, but Java doesn't have function pointers. What's my best alternative?
Anonymous inner class
Say you want to have a function passed in with a String param that returns an int.
First you have to define an interface with the function as its only member, if you can't reuse an existing one.
interface StringFunction {
int func(String param);
}
A method that takes the pointer would just accept StringFunction instance like so:
public void takingMethod(StringFunction sf) {
int i = sf.func("my string");
// do whatever ...
}
And would be called like so:
ref.takingMethod(new StringFunction() {
public int func(String param) {
// body
}
});
EDIT: In Java 8, you could call it with a lambda expression:
ref.takingMethod(param -> bodyExpression);
For each "function pointer", I'd create a small functor class that implements your calculation.
Define an interface that all the classes will implement, and pass instances of those objects into your larger function. This is a combination of the "command pattern", and "strategy pattern".
#sblundy's example is good.
When there is a predefined number of different calculations you can do in that one line, using an enum is a quick, yet clear way to implement a strategy pattern.
public enum Operation {
PLUS {
public double calc(double a, double b) {
return a + b;
}
},
TIMES {
public double calc(double a, double b) {
return a * b;
}
}
...
public abstract double calc(double a, double b);
}
Obviously, the strategy method declaration, as well as exactly one instance of each implementation are all defined in a single class/file.
You need to create an interface that provides the function(s) that you want to pass around. eg:
/**
* A simple interface to wrap up a function of one argument.
*
* #author rcreswick
*
*/
public interface Function1<S, T> {
/**
* Evaluates this function on it's arguments.
*
* #param a The first argument.
* #return The result.
*/
public S eval(T a);
}
Then, when you need to pass a function, you can implement that interface:
List<Integer> result = CollectionUtilities.map(list,
new Function1<Integer, Integer>() {
#Override
public Integer eval(Integer a) {
return a * a;
}
});
Finally, the map function uses the passed in Function1 as follows:
public static <K,R,S,T> Map<K, R> zipWith(Function2<R,S,T> fn,
Map<K, S> m1, Map<K, T> m2, Map<K, R> results){
Set<K> keySet = new HashSet<K>();
keySet.addAll(m1.keySet());
keySet.addAll(m2.keySet());
results.clear();
for (K key : keySet) {
results.put(key, fn.eval(m1.get(key), m2.get(key)));
}
return results;
}
You can often use Runnable instead of your own interface if you don't need to pass in parameters, or you can use various other techniques to make the param count less "fixed" but it's usually a trade-off with type safety. (Or you can override the constructor for your function object to pass in the params that way.. there are lots of approaches, and some work better in certain circumstances.)
Method references using the :: operator
You can use method references in method arguments where the method accepts a functional interface. A functional interface is any interface that contains only one abstract method. (A functional interface may contain one or more default methods or static methods.)
IntBinaryOperator is a functional interface. Its abstract method, applyAsInt, accepts two ints as its parameters and returns an int. Math.max also accepts two ints and returns an int. In this example, A.method(Math::max); makes parameter.applyAsInt send its two input values to Math.max and return the result of that Math.max.
import java.util.function.IntBinaryOperator;
class A {
static void method(IntBinaryOperator parameter) {
int i = parameter.applyAsInt(7315, 89163);
System.out.println(i);
}
}
import java.lang.Math;
class B {
public static void main(String[] args) {
A.method(Math::max);
}
}
In general, you can use:
method1(Class1::method2);
instead of:
method1((arg1, arg2) -> Class1.method2(arg1, arg2));
which is short for:
method1(new Interface1() {
int method1(int arg1, int arg2) {
return Class1.method2(arg1, agr2);
}
});
For more information, see :: (double colon) operator in Java 8 and Java Language Specification §15.13.
You can also do this (which in some RARE occasions makes sense). The issue (and it is a big issue) is that you lose all the typesafety of using a class/interface and you have to deal with the case where the method does not exist.
It does have the "benefit" that you can ignore access restrictions and call private methods (not shown in the example, but you can call methods that the compiler would normally not let you call).
Again, it is a rare case that this makes sense, but on those occasions it is a nice tool to have.
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
class Main
{
public static void main(final String[] argv)
throws NoSuchMethodException,
IllegalAccessException,
IllegalArgumentException,
InvocationTargetException
{
final String methodName;
final Method method;
final Main main;
main = new Main();
if(argv.length == 0)
{
methodName = "foo";
}
else
{
methodName = "bar";
}
method = Main.class.getDeclaredMethod(methodName, int.class);
main.car(method, 42);
}
private void foo(final int x)
{
System.out.println("foo: " + x);
}
private void bar(final int x)
{
System.out.println("bar: " + x);
}
private void car(final Method method,
final int val)
throws IllegalAccessException,
IllegalArgumentException,
InvocationTargetException
{
method.invoke(this, val);
}
}
If you have just one line which is different you could add a parameter such as a flag and a if(flag) statement which calls one line or the other.
You may also be interested to hear about work going on for Java 7 involving closures:
What’s the current state of closures in Java?
http://gafter.blogspot.com/2006/08/closures-for-java.html
http://tech.puredanger.com/java7/#closures
New Java 8 Functional Interfaces and Method References using the :: operator.
Java 8 is able to maintain method references ( MyClass::new ) with "# Functional Interface" pointers. There are no need for same method name, only same method signature required.
Example:
#FunctionalInterface
interface CallbackHandler{
public void onClick();
}
public class MyClass{
public void doClick1(){System.out.println("doClick1");;}
public void doClick2(){System.out.println("doClick2");}
public CallbackHandler mClickListener = this::doClick;
public static void main(String[] args) {
MyClass myObjectInstance = new MyClass();
CallbackHandler pointer = myObjectInstance::doClick1;
Runnable pointer2 = myObjectInstance::doClick2;
pointer.onClick();
pointer2.run();
}
}
So, what we have here?
Functional Interface - this is interface, annotated or not with #FunctionalInterface, which contains only one method declaration.
Method References - this is just special syntax, looks like this, objectInstance::methodName, nothing more nothing less.
Usage example - just an assignment operator and then interface method call.
YOU SHOULD USE FUNCTIONAL INTERFACES FOR LISTENERS ONLY AND ONLY FOR THAT!
Because all other such function pointers are really bad for code readability and for ability to understand. However, direct method references sometimes come handy, with foreach for example.
There are several predefined Functional Interfaces:
Runnable -> void run( );
Supplier<T> -> T get( );
Consumer<T> -> void accept(T);
Predicate<T> -> boolean test(T);
UnaryOperator<T> -> T apply(T);
BinaryOperator<T,U,R> -> R apply(T, U);
Function<T,R> -> R apply(T);
BiFunction<T,U,R> -> R apply(T, U);
//... and some more of it ...
Callable<V> -> V call() throws Exception;
Readable -> int read(CharBuffer) throws IOException;
AutoCloseable -> void close() throws Exception;
Iterable<T> -> Iterator<T> iterator();
Comparable<T> -> int compareTo(T);
Comparator<T> -> int compare(T,T);
For earlier Java versions you should try Guava Libraries, which has similar functionality, and syntax, as Adrian Petrescu has mentioned above.
For additional research look at Java 8 Cheatsheet
and thanks to The Guy with The Hat for the Java Language Specification §15.13 link.
#sblundy's answer is great, but anonymous inner classes have two small flaws, the primary being that they tend not to be reusable and the secondary is a bulky syntax.
The nice thing is that his pattern expands into full classes without any change in the main class (the one performing the calculations).
When you instantiate a new class you can pass parameters into that class which can act as constants in your equation--so if one of your inner classes look like this:
f(x,y)=x*y
but sometimes you need one that is:
f(x,y)=x*y*2
and maybe a third that is:
f(x,y)=x*y/2
rather than making two anonymous inner classes or adding a "passthrough" parameter, you can make a single ACTUAL class that you instantiate as:
InnerFunc f=new InnerFunc(1.0);// for the first
calculateUsing(f);
f=new InnerFunc(2.0);// for the second
calculateUsing(f);
f=new InnerFunc(0.5);// for the third
calculateUsing(f);
It would simply store the constant in the class and use it in the method specified in the interface.
In fact, if KNOW that your function won't be stored/reused, you could do this:
InnerFunc f=new InnerFunc(1.0);// for the first
calculateUsing(f);
f.setConstant(2.0);
calculateUsing(f);
f.setConstant(0.5);
calculateUsing(f);
But immutable classes are safer--I can't come up with a justification to make a class like this mutable.
I really only post this because I cringe whenever I hear anonymous inner class--I've seen a lot of redundant code that was "Required" because the first thing the programmer did was go anonymous when he should have used an actual class and never rethought his decision.
The Google Guava libraries, which are becoming very popular, have a generic Function and Predicate object that they have worked into many parts of their API.
One of the things I really miss when programming in Java is function callbacks. One situation where the need for these kept presenting itself was in recursively processing hierarchies where you want to perform some specific action for each item. Like walking a directory tree, or processing a data structure. The minimalist inside me hates having to define an interface and then an implementation for each specific case.
One day I found myself wondering why not? We have method pointers - the Method object. With optimizing JIT compilers, reflective invocation really doesn't carry a huge performance penalty anymore. And besides next to, say, copying a file from one location to another, the cost of the reflected method invocation pales into insignificance.
As I thought more about it, I realized that a callback in the OOP paradigm requires binding an object and a method together - enter the Callback object.
Check out my reflection based solution for Callbacks in Java. Free for any use.
Sounds like a strategy pattern to me. Check out fluffycat.com Java patterns.
oK, this thread is already old enough, so very probably my answer is not helpful for the question. But since this thread helped me to find my solution, I'll put it out here anyway.
I needed to use a variable static method with known input and known output (both double). So then, knowing the method package and name, I could work as follows:
java.lang.reflect.Method Function = Class.forName(String classPath).getMethod(String method, Class[] params);
for a function that accepts one double as a parameter.
So, in my concrete situation I initialized it with
java.lang.reflect.Method Function = Class.forName("be.qan.NN.ActivationFunctions").getMethod("sigmoid", double.class);
and invoked it later in a more complex situation with
return (java.lang.Double)this.Function.invoke(null, args);
java.lang.Object[] args = new java.lang.Object[] {activity};
someOtherFunction() + 234 + (java.lang.Double)Function.invoke(null, args);
where activity is an arbitrary double value. I am thinking of maybe doing this a bit more abstract and generalizing it, as SoftwareMonkey has done, but currently I am happy enough with the way it is. Three lines of code, no classes and interfaces necessary, that's not too bad.
To do the same thing without interfaces for an array of functions:
class NameFuncPair
{
public String name; // name each func
void f(String x) {} // stub gets overridden
public NameFuncPair(String myName) { this.name = myName; }
}
public class ArrayOfFunctions
{
public static void main(String[] args)
{
final A a = new A();
final B b = new B();
NameFuncPair[] fArray = new NameFuncPair[]
{
new NameFuncPair("A") { #Override void f(String x) { a.g(x); } },
new NameFuncPair("B") { #Override void f(String x) { b.h(x); } },
};
// Go through the whole func list and run the func named "B"
for (NameFuncPair fInstance : fArray)
{
if (fInstance.name.equals("B"))
{
fInstance.f(fInstance.name + "(some args)");
}
}
}
}
class A { void g(String args) { System.out.println(args); } }
class B { void h(String args) { System.out.println(args); } }
Check out lambdaj
http://code.google.com/p/lambdaj/
and in particular its new closure feature
http://code.google.com/p/lambdaj/wiki/Closures
and you will find a very readable way to define closure or function pointer without creating meaningless interface or use ugly inner classes
Wow, why not just create a Delegate class which is not all that hard given that I already did for java and use it to pass in parameter where T is return type. I am sorry but as a C++/C# programmer in general just learning java, I need function pointers because they are very handy. If you are familiar with any class which deals with Method Information you can do it. In java libraries that would be java.lang.reflect.method.
If you always use an interface, you always have to implement it. In eventhandling there really isn't a better way around registering/unregistering from the list of handlers but for delegates where you need to pass in functions and not the value type, making a delegate class to handle it for outclasses an interface.
None of the Java 8 answers have given a full, cohesive example, so here it comes.
Declare the method that accepts the "function pointer" as follows:
void doCalculation(Function<Integer, String> calculation, int parameter) {
final String result = calculation.apply(parameter);
}
Call it by providing the function with a lambda expression:
doCalculation((i) -> i.toString(), 2);
If anyone is struggling to pass a function that takes one set of parameters to define its behavior but another set of parameters on which to execute, like Scheme's:
(define (function scalar1 scalar2)
(lambda (x) (* x scalar1 scalar2)))
see Pass Function with Parameter-Defined Behavior in Java
Since Java8, you can use lambdas, which also have libraries in the official SE 8 API.
Usage:
You need to use a interface with only one abstract method.
Make an instance of it (you may want to use the one java SE 8 already provided) like this:
Function<InputType, OutputType> functionname = (inputvariablename) {
...
return outputinstance;
}
For more information checkout the documentation: https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html
Prior to Java 8, nearest substitute for function-pointer-like functionality was an anonymous class. For example:
Collections.sort(list, new Comparator<CustomClass>(){
public int compare(CustomClass a, CustomClass b)
{
// Logic to compare objects of class CustomClass which returns int as per contract.
}
});
But now in Java 8 we have a very neat alternative known as lambda expression, which can be used as:
list.sort((a, b) -> { a.isBiggerThan(b) } );
where isBiggerThan is a method in CustomClass. We can also use method references here:
list.sort(MyClass::isBiggerThan);
The open source safety-mirror project generalizes some of the above mentioned solutions into a library that adds functions, delegates and events to Java.
See the README, or this stackoverflow answer, for a cheat sheet of features.
As for functions, the library introduces a Fun interface, and some sub-interfaces that (together with generics) make up a fluent API for using methods as types.
Fun.With0Params<String> myFunctionField = " hello world "::trim;`
Fun.With2Params<Boolean, Object, Object> equals = Objects::equals;`
public void foo(Fun.With1ParamAndVoid<String> printer) throws Exception {
printer.invoke("hello world);
}
public void test(){
foo(System.out::println);
}
Notice:
that you must choose the sub-interface that matches the number of parameters in the signature you are targeting. Fx, if it has one parameter, choose Fun.With1Param.
that Generics are used to define A) the return type and B) the parameters of the signature.
Also, notice that the signature of the Method Reference passed to the call to the foo() method must match the the Fun defined by method Foo. If it do not, the compiler will emit an error.

Categories

Resources