Guava学习笔记--02. EventBus使用

Guava EventBus

EventBus 是Guava的一个发布订阅的模型,先看一个简单的实现:

  1. 定义一个Event的消息传递对象

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18

    public class TestEvent1 {
    private final int message;

    /**
    * 构造方法
    * @param message
    */
    public TestEvent1(int message) {
    this.message = message;
    // System.out.println("TestEvent1 事件message:"+message);
    }

    public int getMessage() {
    return message;
    }
    }

  1. 定义一个Listener

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    public class EventListener {
    public int lastMessage = 0;

    @Subscribe
    public void listen(TestEvent1 event) {
    lastMessage = event.getMessage();
    System.out.println("Message:"+lastMessage);
    }

    public int getLastMessage() {
    return lastMessage;
    }
    }

阅读更多

Guava学习笔记--01. Joiner使用

对于Guava的认识来自于阅读QMQ源码的时候,有很多没有使用过的Java方法和集合,所以就查了查,发现是用的是Guava的类库,所以就有了下面的博客:

1. 字符串的拼接

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
 
private final List<String> stringList = Arrays.asList("Google", "Guava", "Java", "Scala", "Kafka");
private final List<String> stringListWithNullValue = Arrays.asList("Google", "Guava", "Java", "Scala", null);


//1. 字符串的拼接
@Test
public void Test() {
String join = Joiner.on("*").join(stringList);
System.out.println(join);
assertEquals(join, "Google*Guava*Java*Scala*Kafka");
}

@Test(expected = NullPointerException.class)
public void TestJoinValue() {
String join = Joiner.on("*").join(stringListWithNullValue);
System.out.println(join);
assertEquals(join, "Google*Guava*Java*Scala*Kafka");
}
阅读更多