本文共 3037 字,大约阅读时间需要 10 分钟。
之所以将匿名内部类和回调函数两个知识点一起写,是因为最近学习zookeeper的时候正好遇到这么一个例子。详细内容请参考:https://www.w3cschool.cn/zookeeper/zookeeper_api.html
以下是与ZooKeeper集合连接的完整代码。
public class ZooKeeperConnection { // declare zookeeper instance to access ZooKeeper ensemble private ZooKeeper zoo; final CountDownLatch connectedSignal = new CountDownLatch(1); // Method to connect zookeeper ensemble. public ZooKeeper connect(String host) throws IOException,InterruptedException { zoo = new ZooKeeper(host,5000,new Watcher() { public void process(WatchedEvent we) { if (we.getState() == KeeperState.SyncConnected) { connectedSignal.countDown(); } } }); connectedSignal.await(); return zoo; } // Method to disconnect from zookeeper server public void close() throws InterruptedException { zoo.close(); }}
匿名内部类的创建格式如下:
new 父类构造器(参数列表)|实现接口() { //匿名内部类的类体部分 }
在上面的代码中,connect方法中在实例化ZooKeeper对象时用到了匿名内部类:
zoo = new ZooKeeper(host,5000,new Watcher() { public void process(WatchedEvent we) { if (we.getState() == KeeperState.SyncConnected) { connectedSignal.countDown(); } } });
这个内部类没有自己的名字,而是用到了Watcher接口,而通常情况下接口是不能用new的,但是在匿名内部类中可以这样。匿名内部类的类体是一个名为process的方法,这个方法就是用来实现Watcher接口中定义的process抽象方法的。
在这个匿名内部类中恰好又运用了回调函数(又叫回调方法)。
public class XyzWatcher implements Watcher { @Override public void process(WatchedEvent watchedEvent) { final CountDownLatch connectedSignal = new CountDownLatch(1); if (watchedEvent.getState() == Event.KeeperState.SyncConnected) { connectedSignal.countDown(); } try { connectedSignal.await(); } catch (InterruptedException e) { e.printStackTrace(); } }}原来的类ZooKeeperConnection改为如下:
public class ZooKeeperConnection { // declare zookeeper instance to access ZooKeeper ensemble private ZooKeeper zoo; //public final CountDownLatch connectedSignal = new CountDownLatch(1); // Method to connect zookeeper ensemble. XyzWatcher xyz = new XyzWatcher(); public ZooKeeper connect(String host) throws IOException,InterruptedException { zoo = new ZooKeeper(host,5000,xyz); return zoo; } // Method to disconnect from zookeeper server public void close() throws InterruptedException { zoo.close(); }}
转载地址:http://xqtbx.baihongyu.com/