4

It us useful to emulate lambda in Java but currently you must implement in-place class which implement some interface...

For example a join function may get Stringator interface, so can join any 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 any standard Stringator or ToStringer interface...

This join implementation can simplify beans manipulation. For exanple to get list of books:

List<Book> books = ...;
String list =
  join(books, ", ", new Stringator<Book>{ toString(Book b) {return b.getName();} });

Note that suggestion to use standard toString violate Java convention: toString for debugging (look for JavaDoc and Java lang spec)!

UPDATE Java already have interface which work in other direction - PropertyEditor. Each it implementation can construct Object from String. I look for String from Object...

UPDATE 2. Many people think that I wrongly avoid toString. This is from Java 7 Lang Spec (section 6.1):

A method that converts its object to a particular format F should be named
toF. Examples are the method toString of class Object and the methods
toLocaleString and toGMTString of class java.util.Date.

So if I have Book objects, toString naturally must return ISBN, but that if I need to join book titles? That is why toString not so good and java.text.Format.format or other looks more natural.

4

4 回答 4

2

Override toString(),它不违反任何 java 约定,实际上是推荐的做法。

返回对象的字符串表示形式。通常,toString 方法返回一个“以文本方式表示”该对象的字符串。结果应该是一个简洁但信息丰富的表示,易于人们阅读。建议所有子类重写此方法

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

于 2013-04-05T14:36:22.467 回答
1

std java中没有ToStringer之类的接口,可以自己定义,使用

String stringValue()

类似于 intValue() longValue() 等,常用于 java

于 2013-04-05T14:15:59.413 回答
1

有,java.text.Format.format但不是很好,是抽象类。

Java SE 8 可能会有一个函子接口,用于在两种任意类型之间进行转换,其中一种可能是String.

于 2013-04-05T14:25:08.050 回答
1

toString()除了这样一个事实之外,覆盖没有任何问题,它只为您提供了一种将对象表示为字符串的方式。我认为 ganvenkoa 提出的建议可以让您轻松地以自定义方式表达它。想象一下,如果您正在处理一个返回的Customer对象,但是当您使用 加入一群客户时,您希望将客户表示为。toString()John Smithjoin(...)Smith, John

我用于这类事情的一件事是一个实用程序,例如com.google.common.collect.Iterables.transform(Iterable)(它反过来使用 a Function)并将其结果传递给com.google.common.base.Joiner.join(Iterable). 我希望 Java 8 会变得更加优雅

于 2013-04-05T14:54:40.843 回答