package com.dw.guava.base;
import com.google.common.base.Optional;
public class OptinalTutorial {
/**
* main函数第一句 findProductByName()分别传入参数"TV"和"TVS"查看效果
*/
public static void main(String[] args) {
Optional<Product> result = findProductByName("TV");
if (result.isPresent()) {
System.out.println(result.get().getName());
} else {
System.out.println(Optional.absent());
}
result = result.or(Optional.of(new Product("PC")));
System.out.println(result.get().getName());
Product p = findProductByName("bb").orNull();
System.out.println(p);
}
public static Optional<Product> findProductByName(String name) {
if (name.equals("TV")) {
return Optional.of(new Product("TV"));
} else {
return Optional.fromNullable(null);
}
}
}
class Product {
private String name;
public Product() { }
public Product(String name) { this.name = name; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
}