ジェネリクスとApache Commons Collections
- 本家から分離して、ジェネリクス対応を
Commons-Collections with Generics
というプロジェクトで開発しているらしい。
Commons-Collections with Generics download | SourceForge.net
// ICode.java import org.apache.commons.collections15.Transformer; public interface ICode<K> { K getCode(); class Trans<K> implements Transformer<ICode<K>, K> { /** {@inheritDoc} */ @Override public K transform(final ICode<K> input) { return input.getCode(); } } }
// IName.java import org.apache.commons.collections15.Transformer; public interface IName { String getName(); class Trans implements Transformer<IName, String> { /** {@inheritDoc} */ @Override public String transform(final IName input) { return input.getName(); } } }
// Person.java public class Person implements ICode<String>, IName { private String code; private String name; /* コンストラクタやセッターは略 */ public String getCode() { return code; } String getName() { return name; } }
// Hoge.java public class Hoge implements ICode<Integer> { private Integer code; /* コンストラクタやセッターは略 */ public Integer getCode() { return code; } }
// Main.java import java.util.Collection; import java.util.List; import java.util.LinkedList; import org.apache.commons.collections15.CollectionUtils; public class Main { public static void main(String[] args) { List<Person> p = new LinkedList<>(); // p.add(new Person());... Collection<Stirng> c = CollectionUtils.collect(p, new ICode.Trans<String>());//←Person#getCode()の集まり Collection<Stirng> n = CollectionUtils.collect(p, new IName.Trans());//←Person#getName()の集まり //-- List<Hoge> h = new LinkedList<>(); // h.add(new Hoge());... Collection<Integer> i = CollectionUtils.collect(h, new ICode.Trans<Integer>());//←Hoge#getCode()の集まり } }