简体   繁体   中英

Java Anonymous Interface implementation in Ruby

I want to convert following java Anonymous Interface implementation in Ruby. I am new to Ruby coding.

DiscoveryHandler discoveryHandler = new DiscoveryHandler() {
    List<DiscoveredPrinter> printers = new ArrayList<DiscoveredPrinter>();

    public void foundPrinter(DiscoveredPrinter printer) {
        printers.add(printer);
    }

    public void discoveryFinished() {
        for (DiscoveredPrinter printer : printers) {
            System.out.println(printer);
        }
        System.out.println("Discovered " + printers.size() + " printers.");
    }

    public void discoveryError(String message) {
        System.out.println("An error occurred during discovery : " + message);
    }
};

Where DiscoveryHandler is an Java Interface which has three methods in it. 1. foundPrinter() 2. discoverFinished() 3. discoveryError() which I think, should be overridden when its instance (in above case discoveryHandler) is created. I am not sure. Thanks in advance.

if the interface has just one method (or its a Java 8 functional one) you can implement it simply by using a block on a place were a method takes a DiscoveryHandler as its last argument eg :

someJavaObject.registerHandler do |printer| # foundPrinter(printer)
  printers.add printer # assuming registerHandler(DiscoveryHandler)
end

its also possible to implement multiple interfaces methods using a single block, in which case you get the Java method name as the first block parameter.

from you sample its not clear what the interface methods are and you seem to be it seems that you do not have a use case for the JRuby block-to-iface conversion, esp. since you're holding a state.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM