SelfCopy.java

package org.genesys.server.model.genesys;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SelfCopy {
	private static final Logger LOG = LoggerFactory.getLogger(SelfCopy.class);
	private static Map<Method, Method> gettersSetters = new HashMap<>();

	static {
		final Method[] allMethods = AccessionData.class.getMethods();
		for (final Method getter : allMethods) {
			String name = getter.getName();
			boolean isGet = false;

			if (name.startsWith("get")) {
				isGet = true;
				name = name.substring(3);
			} else if (name.startsWith("is") && getter.getReturnType().equals(Boolean.class)) {
				isGet = true;
				name = name.substring(2);
			}

			if (isGet) {
				if (LOG.isTraceEnabled()) {
					LOG.trace("Finding setter for getter {}", getter);
				}
				try {
					final Method setter = AccessionData.class.getMethod("set" + name, getter.getReturnType());
					gettersSetters.put(getter, setter);
					LOG.debug("Found setter {}", setter);
				} catch (NoSuchMethodException | SecurityException e) {
					LOG.warn("No setter for {}", name);
				}
			}
		}
	}

	public static void copy(final AccessionData source, final AccessionData target) {
		for (final var entry : gettersSetters.entrySet()) {
			try {
				final Object val = entry.getKey().invoke(source);
				entry.getValue().invoke(target, val);
			} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
				LOG.warn(e.getMessage(), e);
			}
		}
	}

}