1 package org.simantics.g3d.objmap.rules.range;
\r
3 import java.lang.reflect.InvocationTargetException;
\r
4 import java.lang.reflect.Method;
\r
5 import java.util.ArrayList;
\r
6 import java.util.Collection;
\r
8 import org.simantics.objmap.MappingException;
\r
9 import org.simantics.objmap.rules.range.IRangeAccessor;
\r
12 * Accessor for mapped collections.
\r
13 * Uses three methods:
\r
14 * - Getter: returns the collection.
\r
15 * - Adder: adds one item into the collection.
\r
16 * - Remover: removes one item from the collection.
\r
18 * @author Marko Luukkainen <marko.luukkainen@vtt.fi>
\r
22 public class CollectionAccessor<T> implements IRangeAccessor<Collection<T>> {
\r
24 private Method getter;
\r
25 private Method adder;
\r
26 private Method remover;
\r
28 public CollectionAccessor(Method getter, Method adder, Method remover) {
\r
29 this.getter = getter;
\r
31 this.remover = remover;
\r
34 @SuppressWarnings("unchecked")
\r
35 public java.util.Collection<T> get(Object element) throws org.simantics.objmap.MappingException {
\r
37 return (Collection<T>) getter.invoke(element);
\r
38 } catch (IllegalArgumentException e) {
\r
39 throw new MappingException(e);
\r
40 } catch (IllegalAccessException e) {
\r
41 throw new MappingException(e);
\r
42 } catch (InvocationTargetException e) {
\r
43 throw new MappingException(e);
\r
48 public boolean set(Object element, Collection<T> value)
\r
49 throws MappingException {
\r
50 java.util.Collection<T> current = get(element);
\r
51 Collection<T> adding = new ArrayList<T>();
\r
52 Collection<T> removing = new ArrayList<T>();
\r
53 for (T e : current) {
\r
54 if (!value.contains(e))
\r
58 if (!current.contains(e))
\r
63 for (T e : removing) {
\r
64 remover.invoke(element, e);
\r
67 for (T e : adding) {
\r
68 adder.invoke(element, e);
\r
70 } catch (IllegalArgumentException e) {
\r
71 throw new MappingException(e);
\r
72 } catch (IllegalAccessException e) {
\r
73 throw new MappingException(e);
\r
74 } catch (InvocationTargetException e) {
\r
75 throw new MappingException(e);
\r