generics - Are there any standard interface for converting Object to String in Java? -


it useful emulate lambda in java must implement in-place class implement interface...

for example join function may stringator interface, can join list or collection regardless of contained object:

interface stringator<t> { string tostring(t t); }  public static <t> string join(collection<t> col, string delim, stringator<t> s) {     stringbuilder sb = new stringbuilder();     iterator<t> iter = col.iterator();     if (iter.hasnext())         sb.append(s.tostring(iter.next()));     while (iter.hasnext()) {         sb.append(delim);         sb.append(s.tostring(iter.next()));     }     return sb.tostring(); } 

i don't know standard stringator or tostringer interface...

this join implementation can simplify beans manipulation. exanple list of books:

list<book> books = ...; string list =   join(books, ", ", new stringator<book>{ tostring(book b) {return b.getname();} }); 

note suggestion use standard tostring violate java convention: tostring debugging (look javadoc , java lang spec)!

update java have interface work in other direction - propertyeditor. each implementation can construct object string. string object...

update 2. many people think wrongly avoid tostring. java 7 lang spec (section 6.1):

a method converts object particular format f should named tof. examples method tostring of class object , methods tolocalestring , togmtstring of class java.util.date. 

so if have book objects, tostring naturally must return isbn, if need join book titles? why tostring not , java.text.format.format or other looks more natural.

override tostring(), not violate java conventions , recommended practice.

returns string representation of object. in general, tostring method returns string "textually represents" object. result should concise informative representation easy person read. it recommended subclasses override method.

http://docs.oracle.com/javase/6/docs/api/java/lang/object.html#tostring%28%29


Comments

Popular posts from this blog

monitor web browser programmatically in Android? -

Shrink a YouTube video to responsive width -

wpf - PdfWriter.GetInstance throws System.NullReferenceException -