我希望在对象列表中实现一个功能,因为我会在c#中使用扩展方法。

就像这样:

List<DataObject> list;
// ... List initialization.
list.getData(id);

在Java中怎么做呢?


当前回答

可以使用面向对象的装饰器设计模式。在Java的标准库中使用这种模式的一个例子是DataOutputStream。

下面是一些增强List功能的代码:

public class ListDecorator<E> implements List<E>
{
    public final List<E> wrapee;

    public ListDecorator(List<E> wrapee)
    {
        this.wrapee = wrapee;
    }

    // implementation of all the list's methods here...

    public <R> ListDecorator<R> map(Transform<E,R> transformer)
    {
        ArrayList<R> result = new ArrayList<R>(size());
        for (E element : this)
        {
            R transformed = transformer.transform(element);
            result.add(transformed);
        }
        return new ListDecorator<R>(result);
    }
}

附注:我是Kotlin的忠实粉丝。它有扩展方法,也运行在JVM上。

其他回答

Java没有这样的特性。 相反,你可以创建列表实现的常规子类或创建匿名内部类:

List<String> list = new ArrayList<String>() {
   public String getData() {
       return ""; // add your implementation here. 
   }
};

问题是调用这个方法。你可以“就地”做:

new ArrayList<String>() {
   public String getData() {
       return ""; // add your implementation here. 
   }
}.getData();

这个问题有点晚了,但如果有人发现它有用,我只是创建了一个子类:

public class ArrayList2<T> extends ArrayList<T> 
{
    private static final long serialVersionUID = 1L;

    public T getLast()
    {
        if (this.isEmpty())
        {
            return null;
        }
        else
        {       
            return this.get(this.size() - 1);
        }
    }
}

可以使用面向对象的装饰器设计模式。在Java的标准库中使用这种模式的一个例子是DataOutputStream。

下面是一些增强List功能的代码:

public class ListDecorator<E> implements List<E>
{
    public final List<E> wrapee;

    public ListDecorator(List<E> wrapee)
    {
        this.wrapee = wrapee;
    }

    // implementation of all the list's methods here...

    public <R> ListDecorator<R> map(Transform<E,R> transformer)
    {
        ArrayList<R> result = new ArrayList<R>(size());
        for (E element : this)
        {
            R transformed = transformer.transform(element);
            result.add(transformed);
        }
        return new ListDecorator<R>(result);
    }
}

附注:我是Kotlin的忠实粉丝。它有扩展方法,也运行在JVM上。

Project Lombok提供了一个注释@ExtensionMethod,可用于实现您所要求的功能。

XTend语言(它是Java的超级集,可编译为Java源代码1)支持这一点。