Java 8 Method Reference more than one different constructors - java

I'm trying to write a method that takes a constructor of a Runnable class and runs it in a certain way, according to the constructor that was input.
So I want to be able to do something like this:
executeInParallel(someRunnable::new)
executeInParallel(someOtherRunnable::new)
My question is how do I define the executeInParallel method in order to be able to pass any of the Runnable constructors I've defined in the parameters? Essentially my question is in order to do that what how do I define this method?
void executeInParallel(??){ ... }
It seems that I can only have methods that adhere to a Functional Interface as parameters though, so I can't define executeInParallel with a single parameter that accepts more than one xRunnable::new constructors Is there a way for me to do this without using some sort of a Factory pattern?
I want to make clear that the reason I want to do this is that I want to pass in constructors and not instances. I can't generate the instance outside executeInParallel, it has to be generated inside that method. I also want to pass in different constructors that take different parameters
Thank you in advance
EDIT
Sorry, I made the question a little more clear hopefully.

Your executeInParallel() method accepts something that will generate a Runnable, so its signature should be executeInParallel(Supplier<? extends Runnable> runnableFactory)
Then, you can call it with any lambda or method reference that can return an instance of any class that implements Runnable.
Possible usages :
// Ex 1 :
class MyJob implements Runnable {
public void run() {...}
}
executeInParallel(() -> new MyJob());
executeInParallel(MyJob::new);
// Ex 2 :
class MyJobWithParams implements Runnable {
public MyJobWithParams(String param1, int param2) { ... }
public void run() {...}
}
executeInParallel( () -> new MyJobWithParams("Hello",42) );
// You cannot use method references here
// Ex 3 :
class RunnableFactory {
public static Runnable makeRunnable() {
return new MyJob(); // which is a Runnable, see above
}
}
executeInParallel( () -> RunnableFactory.makeRunnable() );
executeInParallel( RunnableFactory::makeRunnable );
Also, you state that you only want Runnable constructors to be passed to the method. This can be done via a method reference (but only for a no-arg constructor), or via a lambda expression (like in example #1 and #2 above).

Related

Why shouldn't i change the interface method names when implementing them?

Say I'm using a Runnable interface,
Runnable runnable = new Runnable() {
#Override
public void run() {
// some code
}
};
If the run () method in Runnable interface is empty , why should we use #Override and same name for the method in our code instead of just using a random name for our implementation like ,
Runnable runnable = new Runnable() {
public void myRun() {
// some code
}
};
The question might seem dumb but I'm a newbie to programming!
Runnable has only one method, thus, you may be tempted to think the method name is irrelevant. But most interfaces have more than one method. For example, java.util.Iterator which has 2 (well, 4, but 2 of those have default impls so you don't need to implement those. Point is, 2 that you must implement).
So, let's say that instead of naming your two methods next and hasNext, you name them jill and jane instead.
How is the compiler or any caller supposed to figure out which one performs the hasNext job and which one performs the next job? Look at the signatures? What if your interface has 2 different methods with the exact same signature?
Not possible. That's why the names need to match: They are used to look this up.
Yes, if the interface has just the one name you'd think the compiler/caller can just go: Yeah, well, the one and only method it has, that's the one. But that's not how it works - language design is simpler if you avoid making exceptions just for simplified cases.
Note that java has lambda syntax, which only works when an interface has one method, and which omit the method name entirely, as well as the argument types. Instead of your myRun method you could write this too:
Runnable r = () -> /* some code */;
No new Runnable() { public void myRun, and no }} required. If myRun had arguments, you don't even need to add their types, just their names. For example, Comparator, which has arguments:
long form:
Comparator<String> lengthComparator = new Comparator<String>() {
#Override public int compare(String a, String b) {
return a.length() - b.length();
}
};
can be written much shorter:
Comparator<String> lengthComparator = (a, b) -> a.length() - b.length();
Think about what it means to "implement an interface". If I have a variable of an interface type, I can call any method defined in the interface on that variable. For example, for the Runnable interface:
interface Runnable {
void run();
}
If I have a variable of type Runnable, I know I can call run on it:
Runnable r = ...;
r.run(); // I can guarantee this will work, because whatever "..." evaluates to, implements Runnable
So when you implement Runnable, you are really just saying that "this class has a run method". The Java compiler also checks that what you are saying is true, that the class actually has a run method. Saying false things about your class, intuitively, should not be allowed, right?
We can also think about what would happen if you were allowed to implement Runnable, but not provide a run method, then you would not be 100% sure that any variable of type Runnable has a run method.
class TrueRunnable implements Runnable {
#Override public void run() {}
}
class FakeRunnable implements Runnable { // suppose this is allowed
public void myRun() {}
}
...
Runnable r;
if (new Random().nextBoolean()) {
r = new TrueRunnable()
} else {
r = new FakeRunnable();
}
// does r have a run method? Maybe.
Then interfaces would not be very useful, because you are not 100% sure whether any Object has any method anyway.
Object r;
if (new Random().nextBoolean()) {
r = new TrueRunnable()
} else {
r = new FakeRunnable();
}
// does r have a run method? Maybe.
So in that case we would lose the whole point of using interfaces.
As to why an interface implementation method has to have the same name as the declaration method name in the interface , i think it boils down to allowing Java compiler to understand which method actually implements the interface. Otherwise its impossible for the Java compiler to know.
Another solution could have been to use a qualifier name in an annotation to signal which is the implementation method something like this.
public interface MyInterface {
void sayHello();
}
and
public class Hello implements MyInterface {
#Implements("MyInterface.sayHello")
public void someOtherName() {
print("Hello World);
}
}
This approach is not valid , but could have been an alternative if Java creators wanted to allow users to declare different names for interface implementation methods. I think this approach is uglier and prone to errors though.
Also this problem does not exist when using lambda expressions where the compiler can understand whats happening without the code writer having to specify the name of the interface method. Note that this only applies to functional interfaces.

How to implement this code using lambda expressions in Java?

I have a software specification document for a specific library in java which helps collecting data from a biosensor and has a class called 'Patch'. The document specifies:
Following is the constructor of Patch class:
Patch(JSONObject options, (JSONObject)->onDiscovery,(JSONObject)->ondata,(JSONObject)->onStatus)
Where
JOSNObject options: options settings for the object
(JSONObject)->onDiscovery: Callback for receiving the sensor info as a JSONObject,
(JSONObject)->ondata: Callback for receiving the sensor data as a JSONObject,
(JSONObject)->onStatus: Callback for receiving the global errors as a JSONObject
It should be called as
Patch patch=newPatch(jsonConfigObject, discoveryObject, streamObject, status);
The concerned fellow stated that these callbacks shall be just lambda expressions.
Now what I understand is:
Constructor takes 4 args:
An empty JSON object,
Callback function reference
Callback function reference
Callback function reference
Am new to Callback implementation so am not able to figure out:
how shall I implement this one in my code?
Do I have to create the functional interfaces for each of those callback methods?
Lets say I have just imported the library, what shall I do next?
The objective of lambda expressions is to denote methods that the Patch-object can call (back) at certain events. In contrast to other programming languages it was not possible to pass functions as parameters to constructors or methods in Java. Thus it was necessary to create an object of a class that implements a certain interface (or is otherwise known to have a certain method by type) and to pass it to the method or constructor as a parameter. The method can then be called at the passed object when the event occurs.
The functional interface is already there. You do not need to create it by yourself. It has been already used in the signature of the constructor of Patch (the types of the last three parameters to the constructor). Functional interfaces are types which have exactly one abstract method that has to be overridden.
Lets suppose the functional interface looks like this:
interface Callback { // could of course have a different name
public void call(JSONObject o);
}
It is not necessary to add the #FunctionalInterface-annotation. It would only prevent the interface from later modifications, namely adding further abstract methods.
It seems reasonable to assume that the abstract method does not have a return value (but you need to check this. When you use lambda expressions you do not need to know what the actual method name (here call) is.
Although most handy it is not necessary to call the constructor with lambda expressions for the last three parameters. Other possibilities include a method reference (using ::), anonymous classes, and instantiating a newly defines class.
Of course you need to know what should happen when the three events occur. Lets say that you have already three methods that provide the necessary functionality. Probably a JSONObject that contains information about the event is necessary to do something useful.
class Main {
static void onDiscovery(JSONObject o) {...}
static void onData(JSONObject o) {...}
static void onStatus(JSONObject o) {...}
}
It is not necessary that the three methods have exactly these names nor that they are static.
In the main method of this class (or somewhere else) could happen:
public static void main(String[] args) {
JSONObject o = // ...
Patch p = new Patch(o,
(x) -> Main.onDiscovery(x), // (1) lambda expr. (Main. can be omitted)
Main::onData, // (2) method reference
new Callback() { // (3) anonymous inner class
public void call(JSONObject x) {
Main.onStatus(x);
}
});
//...
}
(1)-(3) show alternative ways to pass an object of type Callback.
(1) has the advantage that shorter implementations could go right here instead of calling onDiscovery(x). If you have more than one statement you need curly brackets around the statements and ";" after each statement:
(x) -> {
System.out.println("discovery event");
System.out.println(x.getXYZ());
// ...
}
(2) has the advantage to be super concise. If you do not have a static method to reference, a object reference can also be used to denote the object on which the method should be called.
(3) anonymous inner classes are would normally not be used anymore for functional interfaces. If the interface / abstract class has more abstract methods but one it is still necessary to use anonymous inner classes.
class Main {
void onData(JSONObject o) { ... }
// ...
public static void main(String[] args) {
var m = new Main();
var o = new JSONObject(); // or whatever
var p = new Patch(o,
(x) -> m.onDiscovery(x),
m::onData;
new Callback() {
public void call(JSONObject x) {
m.onStatus(x);
}
});
}
}

Calling a method in ExecuterService using double colon (::) [duplicate]

This question already has answers here:
:: (double colon) operator in Java 8
(17 answers)
Closed 2 years ago.
I have a class constitues 2 methods static and non static respectively, as per my limited knowledge submit method accepts runnable,callable instance directly or through lamba expression.
Today I came to know that we can even call or trigger static as well as non static method directly by using double colon which has been added in java 8.
I was just wondering how this works, there is no run method in my class and it doesn't implements runnable and even I'm not using lamba?
Is it a good practice to use :: or one should pass the runnable or callable instance.
Is there any other way to call a method inside submit() rather passing an instance?
Class A {
public static void printSomething(){
System.out.println("Staitc Method");
}
public void print()
{
System.out.println("Non-Staitc Method");
}
}
psvm()
{
A a = new A():
ExecutorService es = Executors.newFixedThreadPool(2);
es.submit(A::printSomething); //Expected is runnable or callable task
es.submit(a::print);
}
A::printSomething is called a method reference. When you use a method reference in a place that expects an interface like Runnable or Callable, Java automatically creates an implementation of that interface that calls the method.
That is,
es.submit(A::printSomething);
behaves the same as
es.submit(new Runnable() {
public void run() {
A.printSomething();
}
});
but is easier to read and does not create a new class everywhere you use it, or a new object instance every time it's called.
You can read more about method references in
The tutorial from Oracle
This write-up on Baeldung
Another way of achieving the same is using lambda expressions such as:
es.submit(() -> A.printSomething());
Since Runnable is a functional interface, you can use lambda expressions or method references that fit it even if the method name doesn't match. Therefore any no-arg void method can be used as a Runnable.
Runnable r1 = () -> a.printSomething();
Runnable r2 = A::printSomething(); // Method reference, short-hand
Runnable r3 = () -> A.printSomething(); // Same as r2, but as explicit lambda expression
The reason why the method reference works even though the class does not implement a void run() method is because what matters for Functional Interface assignment is the method signature and not the method names.
The method signature of A's printSomething matches Runnable's run and for that reason it works. Notice this only works with Functional Interfaces (i.e. those with only one method, said method method not having a default implementation).
Is it good practice? It's a matter of style but it is definitely not bad practice to use method references, and they're also more concise than left -> right lambdas.
I suggest you try this out yourself so you're clear on the rules.
public class FunctionalInterfaceDemo {
public static class SimpleClass {
public static void doItStatic() {
}
public void doItNonStatic() {
}
}
interface MyOwnFunctionalInterface {
void methodA();
}
interface NotAFunctionalInterface {
void methodA();
void methodB();
}
interface AlsoNotAFunctionalInterface {
default void methodA() {
}
}
public static void main(String[] args) {
MyOwnFunctionalInterface compiles = SimpleClass::doItStatic;
MyOwnFunctionalInterface alsoCompiles = new SimpleClass()::doItNonStatic;
NotAFunctionalInterface doesNotCompile = SimpleClass::doItStatic;
AlsoNotAFunctionalInterface alsoDoesNotCompile = SimpleClass::doItStatic;
}
}

How to pass class method as a parameter before the instance is declared?

What I want to do is like this. My question is how can I call tm.test in inner.
// TestMain is a class implemented handler
public void outer() {
inner(TestMain::test); // call inner
}
public void inner(handler h) {
TestMain tm = new TestMain();
//invoke tm.h(), i.e. invoke tm.test() in this example
}
public interface handler<M> {
void entitySelector();
}
I know how to call tm.test in inner if tm is declared in method outer, i.e. pass the function as tm::test
But I have to declare the instance every time I call inner.
Simply spoken: you can't. And even it would be possible, you shouldn't do something like that.
There is the "principle of least surprise": you don't that people reading your code tell you "wtf?!" because your code surprises them.
In other words: you should step back and see if your design really makes sense this way. Can't you use a fixed tm instance for example; one that sits as field on your class; instead of being a local variable in your method?

Can we write a function in Java that takes another function signature as a parameter and executes it? [duplicate]

This may be something common and trivial, but I seem to be having trouble finding a concrete answer. In C# there is a concept of delegates, which relates strongly to the idea of function pointers from C++. Is there a similar functionality in Java? Given that pointers are somewhat absent, what is the best way about this? And to be clear, we're talking first class here.
The Java idiom for function-pointer-like functionality is an an anonymous class implementing an interface, e.g.
Collections.sort(list, new Comparator<MyClass>(){
public int compare(MyClass a, MyClass b)
{
// compare objects
}
});
Update: the above is necessary in Java versions prior to Java 8. Now we have much nicer alternatives, namely lambdas:
list.sort((a, b) -> a.isGreaterThan(b));
and method references:
list.sort(MyClass::isGreaterThan);
You can substitue a function pointer with an interface. Lets say you want to run through a collection and do something with each element.
public interface IFunction {
public void execute(Object o);
}
This is the interface we could pass to some say CollectionUtils2.doFunc(Collection c, IFunction f).
public static void doFunc(Collection c, IFunction f) {
for (Object o : c) {
f.execute(o);
}
}
As an example say we have a collection of numbers and you would like to add 1 to every element.
CollectionUtils2.doFunc(List numbers, new IFunction() {
public void execute(Object o) {
Integer anInt = (Integer) o;
anInt++;
}
});
You can use reflection to do it.
Pass as parameter the object and the method name (as a string) and then invoke the method. For example:
Object methodCaller(Object theObject, String methodName) {
return theObject.getClass().getMethod(methodName).invoke(theObject);
// Catch the exceptions
}
And then use it as in:
String theDescription = methodCaller(object1, "toString");
Class theClass = methodCaller(object2, "getClass");
Of course, check all exceptions and add the needed casts.
No, functions are not first class objects in java. You can do the same thing by implementing a handler class - this is how callbacks are implemented in the Swing etc.
There are however proposals for closures (the official name for what you're talking about) in future versions of java - Javaworld has an interesting article.
This brings to mind Steve Yegge's Execution in the Kingdom of Nouns. It basically states that Java needs an object for every action, and therefore does not have "verb-only" entities like function pointers.
To achieve similar functionality you could use anonymous inner classes.
If you were to define a interface Foo:
interface Foo {
Object myFunc(Object arg);
}
Create a method bar which will receive a 'function pointer' as an argument:
public void bar(Foo foo) {
// .....
Object object = foo.myFunc(argValue);
// .....
}
Finally call the method as follows:
bar(new Foo() {
public Object myFunc(Object arg) {
// Function code.
}
}
Java8 has introduced lambdas and method references. So if your function matches a functional interface (you can create your own) you can use a method reference in this case.
Java provides a set of common functional interfaces. whereas you could do the following:
public class Test {
public void test1(Integer i) {}
public void test2(Integer i) {}
public void consumer(Consumer<Integer> a) {
a.accept(10);
}
public void provideConsumer() {
consumer(this::test1); // method reference
consumer(x -> test2(x)); // lambda
}
}
There is no such thing in Java. You will need to wrap your function into some object and pass the reference to that object in order to pass the reference to the method on that object.
Syntactically, this can be eased to a certain extent by using anonymous classes defined in-place or anonymous classes defined as member variables of the class.
Example:
class MyComponent extends JPanel {
private JButton button;
public MyComponent() {
button = new JButton("click me");
button.addActionListener(buttonAction);
add(button);
}
private ActionListener buttonAction = new ActionListener() {
public void actionPerformed(ActionEvent e) {
// handle the event...
// note how the handler instance can access
// members of the surrounding class
button.setText("you clicked me");
}
}
}
I have implemented callback/delegate support in Java using reflection. Details and working source are available on my website.
How It Works
We have a principle class named Callback with a nested class named WithParms. The API which needs the callback will take a Callback object as a parameter and, if neccessary, create a Callback.WithParms as a method variable. Since a great many of the applications of this object will be recursive, this works very cleanly.
With performance still a high priority to me, I didn't want to be required to create a throwaway object array to hold the parameters for every invocation - after all in a large data structure there could be thousands of elements, and in a message processing scenario we could end up processing thousands of data structures a second.
In order to be threadsafe the parameter array needs to exist uniquely for each invocation of the API method, and for efficiency the same one should be used for every invocation of the callback; I needed a second object which would be cheap to create in order to bind the callback with a parameter array for invocation. But, in some scenarios, the invoker would already have a the parameter array for other reasons. For these two reasons, the parameter array did not belong in the Callback object. Also the choice of invocation (passing the parameters as an array or as individual objects) belongs in the hands of the API using the callback enabling it to use whichever invocation is best suited to it's inner workings.
The WithParms nested class, then, is optional and serves two purposes, it contains the parameter object array needed for the callback invocations, and it provides 10 overloaded invoke() methods (with from 1 to 10 parameters) which load the parameter array and then invoke the callback target.
Check the closures how they have been implemented in the lambdaj library. They actually have a behavior very similar to C# delegates:
http://code.google.com/p/lambdaj/wiki/Closures
Relative to most people here I am new to java but since I haven't seen a similar suggestion I have another alternative to suggest. Im not sure if its a good practice or not, or even suggested before and I just didn't get it. I just like it since I think its self descriptive.
/*Just to merge functions in a common name*/
public class CustomFunction{
public CustomFunction(){}
}
/*Actual functions*/
public class Function1 extends CustomFunction{
public Function1(){}
public void execute(){...something here...}
}
public class Function2 extends CustomFunction{
public Function2(){}
public void execute(){...something here...}
}
.....
/*in Main class*/
CustomFunction functionpointer = null;
then depending on the application, assign
functionpointer = new Function1();
functionpointer = new Function2();
etc.
and call by
functionpointer.execute();

Categories