Created
March 12, 2016 01:58
-
-
Save bartdag/7ce9acf9a202049064a4 to your computer and use it in GitHub Desktop.
Py4J Listener Callback Example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package py4j.examples; | |
public interface ExampleListener { | |
Object notify(Object source); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from py4j.java_gateway import JavaGateway, CallbackServerParameters | |
class PythonListener(object): | |
def __init__(self, gateway): | |
self.gateway = gateway | |
def notify(self, obj): | |
print("Notified by Java") | |
print(obj) | |
gateway.jvm.System.out.println("Hello from python!") | |
return "A Return Value" | |
class Java: | |
implements = ["py4j.examples.ExampleListener"] | |
if __name__ == "__main__": | |
gateway = JavaGateway( | |
callback_server_parameters=CallbackServerParameters()) | |
listener = PythonListener(gateway) | |
gateway.entry_point.registerListener(listener) | |
gateway.entry_point.notifyAllListeners() | |
gateway.shutdown() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package py4j.examples; | |
import py4j.GatewayServer; | |
import java.util.ArrayList; | |
import java.util.List; | |
public class ListenerApplication { | |
List<ExampleListener> listeners = new ArrayList<ExampleListener>(); | |
public void registerListener(ExampleListener listener) { | |
listeners.add(listener); | |
} | |
public void notifyAllListeners() { | |
for (ExampleListener listener: listeners) { | |
Object returnValue = listener.notify(this); | |
System.out.println(returnValue); | |
} | |
} | |
@Override | |
public String toString() { | |
return "<ListenerApplication> instance"; | |
} | |
public static void main(String[] args) { | |
ListenerApplication application = new ListenerApplication(); | |
GatewayServer server = new GatewayServer(application); | |
server.start(true); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment