0. Implements toString() methods
JAVA에서 System.out.println()으로 객체를 출력하면 해당 객체의 toString() method가 호출되어 출력이 됩니다. 해당 method를 override 하지 않았다면 객체의 이름과 Hashcode가 출력이 됩니다. 객체의 맴버 변수가 많을 때 편하게 toString()을 override 해보죠.Apache commons project에 해당 내용이 있습니다.
1. The Commons Lang Package
http://commons.apache.org/proper/commons-lang/
The standard Java libraries fail to provide enough methods for manipulation of its core classes. Apache Commons Lang provides these extra methods.Lang provides a host of helper utilities for the java.lang API, notably String manipulation methods, basic numerical methods, object reflection, concurrency, creation and serialization and System properties. Additionally it contains basic enhancements to java.util.Date and a series of utilities dedicated to help with building methods, such as hashCode, toString and equals.
2. Class ToStringBuilder
아래는 API 문서의 내용입니다. (http://commons.apache.org/proper/commons-lang/javadocs/api-3.1/org/apache/commons/lang3/builder/ToStringBuilder.html)
Assists in implementing이렇게 간단하게 사용하면 됩니다. 이건 JAVA reflection을 사용한 예제 입니다. reflection 이란 쉽게 말해 runtime에 java object의 정보를 가공하거나 가져올 수 있는 기능입니다. JAVA Framework Spring의 dependency injection, eclipse의 자동 완성 기능 같은 것도 이런 reflection API를 JAVA가 제공하기 때문에 가능한 것이죠.Object.toString()methods.
This class enables a good and consistenttoString()to be built for any class or object. This class aims to simplify the process by:
- allowing field names
- handling all types consistently
- handling nulls consistently
- outputting arrays and multi-dimensional arrays
- enabling the detail level to be controlled for Objects and Collections
- handling class hierarchies
public String toString() {이런 형식으로 출력되죠.
return ToStringBuilder.reflectionToString(this);
}
Person@7f54[name=Stephen,age=29,smoker=false]다만 explicitly 하게 사용하는게 성능상 좋다고 합니다.
Alternatively, there is a method that uses reflection to determine the fields to test. Because these fields are usually private, the method,reflectionToString, usesAccessibleObject.setAccessibleto change the visibility of the fields. This will fail under a security manager, unless the appropriate permissions are set up correctly. It is also slower than testing explicitly.
댓글 없음:
댓글 쓰기