개발 관련/Java
Guava 사용 요약 슬라이드.
snoworca
2015. 4. 17. 02:55
이 슬라이드를 보고 암이 치료되었습니다...
위 슬라이드 내용을 아래와 같이 정리해 봤다.
Base :: Objects.equal(), Objects.hashCode(),
MoreObjectes.toStringHelper(), ComparisonChain.compare()
public class Employee implements Comparable{
public String name;
public Integer age;
public Job job;
@Override
public boolean equals(Object o) {
if(!(o instanceof Employee)) return false;
Employee that = (Employee)o;
return Objects.equal(name, that.name) &&
Objects.equal(age, that.age) &&
job == that.job;
}
@Override
public int hashCode() {
return Objects.hashCode(name, age, job);
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this).
add("name", name).
add("age", age).
add("job", job).
toString();
}
@Override
public int compareTo(Employee another) {
return ComparisonChain.start()
.compare(this.name, another.name,
Ordering.natural().nullsLast())
.compare(this.age, another.age,
Ordering.natural().nullsLast())
.compare(this.job, another.job,
Ordering.natural().nullsLast())
.result();
}
}
Base :: Preconditions.checkNotNull()
public class Mail {
String title;
String body;
public Mail(String title, String body) {
this.title = Preconditions.checkNotNull(title, "title must not be null");
this.body = Preconditions.checkNotNull(body, "body must not be null");
Preconditions.checkArgument(body.matches("<[^>]*>"), "Cannot insert tags in body." );
Preconditions.checkArgument(title.matches("<[^>]*>"), "Cannot insert tags in title" );
}
}
// java.lang.NullPointerException: title must not be null 발생.
Mail mailA = new Mail(null, null);
// java.lang.IllegalArgumentException: Cannot insert tags in body. 발생.
Mail mailB = new Mail("ha ha!","hi <div> hello </div> " );
더 많은 정보 : http://stackoverflow.com/questions/3128120/what-is-the-proper-error-message-to-supply-to-google-guavas-preconditions-met
Base :: MoreObjects.firstNonNull()
public String getPackageName() {
// 기존
//String packageName = getPackageName();
//return (packageName != null)?packageName:"UNKNOWN";
// 개선
return MoreObjects.firstNonNull(getPackageName(), "UNKNOWN");
}
Base :: Joiner
List<String> heroes = Lists.newArrayList("Kick-Ass", "Iron Man", null, "Chuck Norris");
String names = Joiner.on(", ").join(heroes);
// NullPointerException 발생!!
List<String> heroes = Lists.newArrayList("Kick-Ass", "Iron Man", null, "Chuck Norris");
String names = Joiner.on(", ").skipNulls().join(heroes);
// "Kick-Ass, Iron Man, Chuck Norris"
List<String> heroes = Lists.newArrayList("Kick-Ass", "Iron Man", null, "Chuck Norris");
String names = Joiner.on(", ").useForNull("Invisible Man").join(heroes);
// prints "Kick-Ass, Iron Man, Invisible Man, Chuck Norris"
Map<Integer, String> map = new HashMap<Integer, String>();
map.put(1, "Chuck Norris");
map.put(2, "Iron Man");
map.put(3, "Kick-Ass");
String ranks = Joiner.on('\n').withKeyValueSeparator(" -> ").join(map);
System.out.println(ranks);
/**
Prints:
1 -> Chuck Norris
2 -> Iron Man
3 -> Kick-Ass
*/
정리중...