Java 8: Interface with single method - java

Sometime I need to make callback from one method to another:
final Integer i = 5;
final Integer j = 10;
foo("arg1", "arg2", (x, y) -> {
/** do sth which need this context **/
bar(i + x, j - y);
})
But in such case I need to write simple interface (somewhere):
public interface someName {
void noMatterName(Integer a, Integer c);
}
Then function foo() can call noMatterName - this is ok. But in simple cases, name of such interfaces and its function is not important. I just want to use lambda with two parameters.
Question:
Do I need to create this interface manually even if I need to make such "communication" between only two function? Does Java provide any similar interface?
Or even something like this:
public interface someName1 {
void noMatterName(Object a);
}
public interface someName2 {
void noMatterName(Object a, Object b);
}

You can use the Consumer<T> (if you need a single parameter), and BiConsumer<T,U> (if you need 2 parameters) functional interfaces.
Interface Consumer<T>
Represents an operation that accepts a single input argument and returns no result.
Interface BiConsumer<T,U>
Represents an operation that accepts two input arguments and returns no result.

Related

Lambda expression using interface in one line

I'm learning about interfaces and I faced a problem which I cannot understand. It's about lambda expression which I learn that can be used in one line, but I've create a case, where this expression does not working and I don't know where I've made a mistake.
I have defined this interface:
public interface MathOperations {
int add(int a, int b);
}
Next I have defined class in which I want to test this interface with adder method.
public class App {
public static void main(String[] args) {
int x;
x = adder((a, b) -> return a+b);
}
public static int adder(MathOperations mo){
return mo.add(3, 5);
}
}
Unfortunately the line with the x assignment doesn't work and I cannot figure out where I've made a mistake. The compiler does not recognize the a and b variable in the return statement. I know that I can make this assignment with brackets but I'm curious if I can do this in one line.
#FunctionalInterface
interface MathOperations {
int add(int a, int b);
}
Here are two ways to do what you want.
To create a lambda, you need to specify the interface type and provide the definition of what to do with a and b.
then you can invoke the lambda and get the value.
MathOperations compute = (a,b)->a+b;
x = compute.add(2,3);
System.out.println(x);
The above does essentially the following behind the scenes.
Here an anonymous class is defined using the interface and instantiated using the new keyword. (the class contains the implemented method).
Implementing the interface was standard until the concept of FuntionalInterfaces and lambdas were introduced in Java 8.
Then call the adder method supplying the instance mo just created or call the method with the previously created compute lambda.
MathOperations mo =new MathOperations() {
public int add(int a,int b) {
return a+b;
}};
System.out.println(adder(mo));
System.out.println(adder(compute));
output of above three print statements
5
8
8
public static int adder(MathOperations mo){
return mo.add(3, 5);
}
Note: Imo, a more versatile interface can be created by following examples from the API functional interfaces already defined. The name MathOperation is fine but the add method is too specific (and functional interfaces may only contain one abstract method). So instead of having an add method, have a compute or similar method and let the name of the lambda dictate its operation.
MathOperation add = (a,b)->a+b;
int sum = add.compute(10,20); // 30
MathOperation sub = (a,b)->a-b;
int diff = sub.compute(10,20) // -10

Differential Functions with Interface in Java

I have to code a Java programm that takes a function like f(x)=2x-5 (but more complex) and evaluates f(x) and differenciate to f'(x). For this I must implement the interface Function:
public interface Function {
double evaluate(double x);
Function differentiate();
}
and implement the interface in several classes like (not correct yet):
public class Constant implements Function {
private final int FS = 0;
#Override
public double evaluate(double n) {
return n;
}
#Override
public Function differentiate() {
return this;
}
public Constant(double value){
evaluate(value);
differentiate();
}
}
that are parts like "product", "sinus", ... that are needed for the programm.
My problem is that I dont know how this should work, because the functions are kind of abstact (because of the unknown x) and the differenciate-method in the interface returns another interface i guess with doesn't make sence to me.
I am a new programmer and hope the get some help here.
Thanks very much!
If one takes this task literally, you will need to write an expression parser that takes a string like "2*sin(x)-5" and translates this into calls that composed amount to
F.Sum(F.Prod(F.Cons(2),F.Sin(F.VarX)),F.Cons(-5))
where F is an instance of a factory class (or a module) where each of the calls returns an implementation of the interface Function for the corresponding abstract function or operation. (Doing it via factory allows book-keeping operations such as checking for duplicated expressions.)
So for instance Product as returned object of F.Prod will need Function objects factor1, factor2 as member fields that are initialized from the constructor arguments. Then the numerical evaluation has to look like (add the usual decorations for a valid function declaration)
evaluate(x) { return factor1.evaluate(x)*factor2.evaluate(x); }
and the symbolic/algorithmic derivative would implement the Leibniz product rule symbolically
differentiate() { return Sum(Product(factor1, factor2.differentiate()), Product(factor1.differentiate(),factor2));
Like said in the comments, the Sine would need one argument Function object in the constructor and stored as member field argument. Then numerical evaluation and symbolic differentiation can look like
evaluate(x) {return Math.sin(argument.evaluate(x)); }
differentiate() { return Product(Cos(argument), argument.differentiate())); }
The last including the inner derivative per the chain rule d/dx(sin(u(x))=cos(u(x))*u'(x).
At the lowest level you need to make a U turn in the evaluation, this can be done sensibly using a VariableX sub-class of Function with
evaluate(x) { return x; }
differentiate { return Constant(1); ]

Avoid code duplication over classes

I am writing some classes and all of them implement a certain method they inherit from an interface. This method is close to the same for all the classes beside one call to a certain other function.
For example:
public void doSomething(){
int a = 6;
int b = 7;
int c = anOtherMethod(a,b);
while(c < 50){
c++;
}
}
What if multiple classes have the function doSomething() but the implementation of the method anOtherMethod() is different?
How do I avoid code duplication in this situation? (This is not my actual code but a simplified version that helps me describe what I mean a bit better.)
This looks like a good example of the template method pattern.
Put doSomething in a base class.
Declare abstract protected anotherMethod in that base class as well, but don't provide an implementation.
Each subclass then provides the proper implementation for anotherMethod.
This is how you could implement the technique that Thilo talked about in the following demo:
Main class:
public class Main extends Method {
public static void main(String[] args) {
Method m = new Main();
m.doSomething();
}
#Override
public int anOtherMethod(int a, int b) {
return a + b;
}
}
Abstact class:
public abstract class Method {
public abstract int anOtherMethod(int a, int b);
public void doSomething() {
int a = 6;
int b = 7;
int c = anOtherMethod(a, b);
System.out.println("Output: "+c);
}
}
This way, all you have to do is override anOtherMethod() in each class that you want to use doSomething() with a different implementation of the method anOtherMethod().
Assuming every version of anOtherFunction takes two integers and returns an integer, I would just have the method accept a function as an argument, making it Higher Order.
A function that takes two arguments of the same type and returns an object of the same type is known as a BinaryOperator. You can add a argument of that type to the method to pass a function in:
// Give the method an operator argument
public void doSomething(BinaryOperator<Integer> otherMethod) {
int a = 6;
int b = 7;
// Then use it here basically like before
// "apply" is needed to call the passed function
int c = otherMethod.apply(a,b);
while(c < 50)
c++;
}
}
How you use it though will depend on your use case. As a simple example using a lambda, you can now call it like:
doSomething((a, b) -> a + b);
Which simply returns the sum of a and b.
For your particular case though, you may find that having doSomething as part of a Interface isn't necessary or optimal. What if instead, anOtherMethod is what's required to be supplied? Instead of expecting your classes to supply a doSomething, have them supply a BinaryOperator<Integer>. Then, when you need to get results from doSomething, get the operator from the class, then pass it to doSomething. Something like:
public callDoSomething(HasOperator obj) {
// There may be a better way than having a "HasOperator" interface
// This is just an example though
BinaryOperator<Integer> f = obj.getOperator();
doSomething(f);
}

When and why would you use Java's Supplier and Consumer interfaces?

As a non-Java programmer learning Java, I am reading about Supplier and Consumer interfaces at the moment. And I can't wrap my head around their usage and meaning.
When and why you would use these interfaces? Can someone give me a simple layperson example of this?
I'm finding the Doc examples not succinct enough for my understanding.
The reason you're having difficulty grasping the meaning of functional interfaces such as those in java.util.function is that the interfaces defined here do not have any meaning! They are present primarily to represent structure, not semantics.
This is atypical for most Java APIs. The typical Java API, such as a class or interface, has meaning, and you can develop a mental model for what it represents and use that to understand the operations on it. Consider java.util.List for example. A List is a container of other objects. They have a sequence and an index. The number of objects contained in the list is returned by size(). Each object has an index in the range 0..size-1 (inclusive). The object at index i can be retrieved by calling list.get(i). And so forth.
The functional interfaces in java.util.function don't have any such meaning. Instead, they're interfaces that merely represent the structure of a function, such as the number of arguments, the number of return values, and (sometimes) whether an argument or return value is a primitive. Thus we have something like Function<T,R> which represents a function that takes a single argument of type T and returns a value of type R. That's it. What does that function do? Well, it can do anything ... as long as it takes a single argument and returns a single value. That's why the specification for Function<T,R> is little more than "Represents a function that accepts one argument and produces a result."
Clearly, when we're writing code, it has meaning, and that meaning has to come from somewhere. In the case of the functional interfaces, the meaning comes from the context in which they're used. The interface Function<T,R> has no meaning in isolation. However, in the java.util.Map<K,V> API, there is the following:
V computeIfAbsent(K key, Function<K,V> mappingFunction)
(wildcards elided for brevity)
Ah, this use of Function is as a "mapping function". What does that do? In this context, if key is not already present in the map, the mapping function is called and is handed the key and is expected to produce a value, and the resulting key-value pair is inserted into the map.
So you can't look at the specification for Function (or any of the other functional interfaces, for that matter) and attempt to discern what they mean. You have to look at where they're used in other APIs to understand what they mean, and that meaning applies only to that context.
This is Supplier:
public Integer getInteger() {
return new Random().nextInt();
}
This is Consumer:
public void sum(Integer a, Integer b) {
System.out.println(a + b);
}
So in layman terms, a supplier is a method that returns some value (as in its return value). Whereas, a consumer is a method that consumes some value (as in method argument), and does some operations on them.
Those will transform to something like these:
// new operator itself is a supplier, of the reference to the newly created object
Supplier<List<String>> listSupplier = ArrayList::new;
Consumer<String> printConsumer = a1 -> System.out.println(a1);
BiConsumer<Integer, Integer> sumConsumer = (a1, a2) -> System.out.println(a1 + a2);
As for usage, the very basic example would be: Stream#forEach(Consumer) method. It takes a Consumer, which consumes the element from the stream you're iterating upon, and performs some action on each of them. Probably print them.
Consumer<String> stringConsumer = (s) -> System.out.println(s.length());
Arrays.asList("ab", "abc", "a", "abcd").stream().forEach(stringConsumer);
A Supplier is any method which takes no arguments and returns a value. Its job is literally to supply an instance of an expected class. For instance, every reference to a 'getter' method is a Supplier
public Integer getCount(){
return this.count;
}
Its instance method reference myClass::getCount is an instance of Supplier<Integer>.
A Consumer is any method which takes arguments and returns nothing. It is invoked for its side-effects. In Java terms, a Consumer is an idiom for a void method. 'setter' methods are a good example:
public void setCount(int count){
this.count = count;
}
Its instance method reference myClass::setCount is an instance of Consumer<Integer> and IntConsumer.
A Function<A,B> is any method which takes an argument of one type, and returns another. This can be referred to as a 'transformation'. The Function<A,B> takes an A and returns a B. Notable is that for a given value of A, the function should always return a specific value of B. A and B can in fact be the same type, such as the following:
public Integer addTwo(int i){
return i+2;
}
Its instance method reference myClass:addTwo is a Function<Integer, Integer> and a ToIntFunction<Integer>.
A Class method reference to a getter is another example of a function.
public Integer getCount(){
return this.count;
}
Its class method reference MyClass::getCount is an instance of Function<MyClass,Integer> and ToIntFunction<MyClass>.
Why are Consumer/Supplier/other functional interfaces defined in java.util.function package: Consumer and Supplier are two, among many, of the in-built functional interfaces provided in Java 8. The purpose of all these in-built functional interfaces is to provide a ready "template" for functional interfaces having common function descriptors(functional method signatures/definitions).
Lets say we have a required to convert a type T to another type R. If we were to pass any function defined like this as a parameter to a method, then that method would need to define a Functional Interface whose functional/abstract method takes parameter of type T as input and gives a parameter of type R as output. Now, there could be many scenarios like this and the programmer(s) would end up defining multiple functional interfaces for their needs. To avoid this kind of a scenario, ease programming & bring a common standard in usage of functional interfaces, a set of in-built functional interfaces such as Predicate, Function, Consumer & Supplier have been defined.
What does Consumer do: Consumer functional interface accepts an input, does something with that input and does not give any output. Its definition is like this (from Java Source) -
#FunctionalInterface
public interface Consumer<T> {
void accept(T t);
}
Here accept() is the functional\abstract method which does takes an input and returns no output. So, if you want to input an Integer, do something with it with no output then instead of defining your own interface use an instance of Consumer.
What does Supplier do: Supplier functional interface does not take any input but returns an output. Its defined like this(from Java Source) -
#FunctionalInterface
public interface Supplier<T> {
T get();
}
Wherever you need a function which returns something, say an Integer, but takes no output use an instance of Supplier.
In case more clarity, along with example usage, of Consumer & Supplier interfaces is needed then you can refer my blog posts on the same - http://www.javabrahman.com/java-8/java-8-java-util-function-consumer-tutorial-with-examples/ and http://www.javabrahman.com/java-8/java-8-java-util-function-supplier-tutorial-with-examples/
1. Meaning
See my answers to my question here and also another here, but in short these new Interfaces provide convention and descriptiveness for everyone to use (+ funky method chaining such as .forEach(someMethod().andThen(otherMethod()))
2. Differences
Consumer: Takes something, does something, returns nothing: void accept(T t)
Supplier: Takes nothing, returns something : T get() (reverse of Consumer, basically a universal 'getter' method)
3. Usage
// Consumer: It takes something (a String) and does something (prints it)
List<Person> personList = getPersons();
personList.stream()
.map(Person::getName)
.forEach(System.out::println);
Supplier: wrap repetitive code, e.g. code execution timing
public class SupplierExample {
public static void main(String[] args) {
// Imagine a class Calculate with some methods
Double result1 = timeMe(Calculate::doHeavyComputation);
Double result2 = timeMe(Calculate::doMoreComputation);
}
private static Double timeMe(Supplier<Double> code) {
Instant start = Instant.now();
// Supplier method .get() just invokes whatever it is passed
Double result = code.get();
Instant end = Instant.now();
Duration elapsed = Duration.between(start,end);
System.out.println("Computation took:" + elapsed.toMillis());
return result;
}
}
Consumer and supplier are the interfaces provided by java. Consumer is use for iterate over the list elements and supplier is use for supply object's
you can easily understand with code demonstration.
Consumer
package com.java.java8;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
/**
* The Class ConsumerDemo.
*
* #author Ankit Sood Apr 20, 2017
*/
public class ConsumerDemo {
/**
* The main method.
*
* #param args
* the arguments
*/
public static void main(String[] args) {
List<String> str = new ArrayList<>();
str.add("DEMO");
str.add("DEMO2");
str.add("DEMO3");
/* Consumer is use for iterate over the List */
Consumer<String> consumer = new Consumer<String>() {
#Override
public void accept(String t) {
/* Print list element on consile */
System.out.println(t);
}
};
str.forEach(consumer);
}
}
Supplier
package com.java.java8;
import java.util.function.Supplier;
/**
* The Class SupplierDemo.
*
* #author Ankit Sood Apr 20, 2017
*/
public class SupplierDemo {
/**
* The main method.
*
* #param args
* the arguments
*/
public static void main(String[] args) {
getValue(() -> "Output1");
getValue(() -> "OutPut2");
}
/**
* Gets the value.
*
* #param supplier
* the supplier
* #return the value
*/
public static void getValue(Supplier<?> supplier) {
System.out.println(supplier.get());
}
}
In Laymen terms,
supplier will supply data but without consuming any data. In programming terms a method which doesn't take any argument but return a value. It is used to generate new values.
http://codedestine.com/java-8-supplier-interface/
consumer will consume data and but do not return any data. In programming terms a method which takes multiple argument and does not return any value.
http://codedestine.com/java-8-consumer-interface/

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