All Downloads are FREE. Search and download functionalities are using the official Maven repository.

de.tsl2.nano.bean.def.ValuePath Maven / Gradle / Ivy

Go to download

TSL2 Framework Descriptor (currency-handling, generic formatter, descriptors for beans, collections, actions and values)

There is a newer version: 2.5.1
Show newest version
/*
 * File: $HeadURL$
 * Id  : $Id$
 * 
 * created by: Tom
 * created on: 16.02.2014
 * 
 * Copyright: (c) Thomas Schneider 2014, all rights reserved
 */
package de.tsl2.nano.bean.def;

import org.simpleframework.xml.Default;
import org.simpleframework.xml.DefaultType;

import de.tsl2.nano.core.cls.BeanAttribute;
import de.tsl2.nano.core.cls.BeanClass;
import de.tsl2.nano.core.cls.IValueAccess;
import de.tsl2.nano.core.messaging.EventController;
import de.tsl2.nano.core.util.CollectionUtil;

/**
 * resolves relations through a path to several beans/attributes
 * 
 * @author Tom
 * @version $Revision$
 */
@SuppressWarnings("unchecked")
@Default(value = DefaultType.FIELD, required = false)
public class ValuePath extends PathExpression implements IValueAccess {
    /** serialVersionUID */
    private static final long serialVersionUID = 1L;
    transient B instance;
    transient EventController eventController;

    protected ValuePath() {
    }

    public ValuePath(B instance, String attributeChain) {
        this((Class) instance.getClass(), instance,
            (Class) Object.class, splitChain(attributeChain));
    }

    /**
     * constructor
     * 
     * @param declaringClass
     * @param attributePath
     * @param instance
     */
    protected ValuePath(Class declaringClass, B instance, Class type, String... attributeChain) {
        super(declaringClass, type, attributeChain);
        this.instance = instance;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public T getValue() {
        return (T) BeanClass.getValue(instance, attributePath);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void setValue(T object) {
        Object lastInstance;
        if (attributePath.length > 1) {
            lastInstance =
                BeanClass.getValue(instance,
                    CollectionUtil.copyOfRange(attributePath, 0, attributePath.length - 2, String[].class));
        } else {
            lastInstance = instance;
        }
        BeanAttribute.getBeanAttribute(BeanClass.getDefiningClass(lastInstance.getClass()),
            attributePath[attributePath.length - 1]).setValue(lastInstance, object);
    }

    /**
     * @param instance The instance to set.
     */
    protected void setInstance(B instance) {
        this.instance = instance;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public EventController changeHandler() {
        if (eventController == null) {
            eventController = new EventController();
        }
        return eventController;
    }
}