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

org.freshvanilla.lang.misc.SafeObjectFieldAccessor Maven / Gradle / Ivy

Go to download

An implementation of OSGi Remote Service Admin, enhanced to provide support for OSGi Promises and streaming using OSGi PushStreams.

The newest version!
package org.freshvanilla.lang.misc;

import java.lang.reflect.Field;

class SafeObjectFieldAccessor implements FieldAccessor {
    private final Field f;

    SafeObjectFieldAccessor(Field f) {
        this.f = f;
    }

    public  Object getField(Pojo pojo) {
    	try {
			return f.get(pojo);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
    }

    public  boolean getBoolean(Pojo pojo) {
        return Boolean.TRUE.equals(getField(pojo));
    }

    public  long getNum(Pojo pojo) {
        Object obj = getField(pojo);
        if (obj instanceof Number) return ((Number)obj).longValue();
        throw new AssertionError("Cannot convert " + obj + " to long.");
    }

    public  double getDouble(Pojo pojo) {
        Object obj = getField(pojo);
        if (obj instanceof Number) return ((Number)obj).doubleValue();
        throw new AssertionError("Cannot convert " + obj + " to double.");
    }

    public  void setField(Pojo pojo, Object value) {
    	try {
        	f.set(pojo, value);
        } catch (Exception e) {
        	throw new RuntimeException();
        }
    }

    public  void setBoolean(Pojo pojo, boolean value) {
    	setField(pojo, value);
    }

    public  void setNum(Pojo pojo, long value) {
    	setField(pojo, value);
    }

    public  void setDouble(Pojo pojo, double value) {
    	setField(pojo, value);
    }
}