X-Git-Url: https://gerrit.simantics.org/r/gitweb?a=blobdiff_plain;ds=sidebyside;f=org.simantics.g3d%2Fsrc%2Forg%2Fsimantics%2Fg3d%2Fobjmap%2Frules%2Frange%2FGetSetValueAccessor.java;fp=org.simantics.g3d%2Fsrc%2Forg%2Fsimantics%2Fg3d%2Fobjmap%2Frules%2Frange%2FGetSetValueAccessor.java;h=f7da6538b2bce2ba6aa96882448a8b7600ffe646;hb=87b3241ec277ba3d8e414b26186a032c9cdcaeed;hp=0000000000000000000000000000000000000000;hpb=1f0bcd66274375f2278d2e6c486cb28257a5f7b2;p=simantics%2F3d.git diff --git a/org.simantics.g3d/src/org/simantics/g3d/objmap/rules/range/GetSetValueAccessor.java b/org.simantics.g3d/src/org/simantics/g3d/objmap/rules/range/GetSetValueAccessor.java new file mode 100644 index 00000000..f7da6538 --- /dev/null +++ b/org.simantics.g3d/src/org/simantics/g3d/objmap/rules/range/GetSetValueAccessor.java @@ -0,0 +1,73 @@ +package org.simantics.g3d.objmap.rules.range; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; + +import org.simantics.objmap.MappingException; +import org.simantics.objmap.rules.range.IRangeAccessor; + +/** + * Accessor for mapped value. Uses two methods: + * - Getter: returns the current value. + * - Setter: sets the current value. The value may be null. (if setter parameter is primitive, null value is not mapped). + * + * @author Marko Luukkainen + * + * @param + */ +public class GetSetValueAccessor implements IRangeAccessor { + + private Method getter; + private Method setter; + private boolean primitive; + + public GetSetValueAccessor(Method getter, Method setter) { + this.getter = getter; + this.setter = setter; + this.primitive = setter.getParameterTypes()[0].isPrimitive(); + } + + @SuppressWarnings("unchecked") + public T get(Object element) throws org.simantics.objmap.MappingException { + try { + return (T) getter.invoke(element); + } catch (IllegalArgumentException e) { + throw new MappingException(e); + } catch (IllegalAccessException e) { + throw new MappingException(e); + } catch (InvocationTargetException e) { + throw new MappingException(e); + } + }; + + @Override + public boolean set(Object element, T value) + throws MappingException { + if (value == null && primitive) + return false; + if (equal(get(element),value)) + return false; + try { + setter.invoke(element, value); + } catch (IllegalArgumentException e) { + throw new MappingException(e); + } catch (IllegalAccessException e) { + throw new MappingException(e); + } catch (InvocationTargetException e) { + throw new MappingException(e); + } + return true; + + } + + private boolean equal(Object v1, Object v2) { + if (v1 == null) { + if (v2 == null) + return true; + return false; + } else if (v2 == null) { + return false; + } + return v1.equals(v2); + } +}