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

com.sap.cds.mt.proxy.ProxyCreator Maven / Gradle / Ivy

/*
 * ----------------------------------------------------------------
 * © 2019-2021 SAP SE or an SAP affiliate company. All rights reserved.
 * ----------------------------------------------------------------
 *
 */

package com.sap.cds.mt.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.HashMap;
import java.util.Map;

public class ProxyCreator {

	@SuppressWarnings("unchecked")
	public static  T create(Class clazz, InvocationHandler invocationHandler) {
		return (T) Proxy.newProxyInstance(clazz.getClassLoader(), new Class[] { clazz }, invocationHandler);
	}

	public static  ProxyBuilder proxy(Class clazz, T instance) {
		return new ProxyBuilder(clazz, instance);
	}

	public static class ProxyBuilder {
		private final Class clazz;
		private final T instance;
		Map substitutes = new HashMap<>();

		public ProxyBuilder(Class clazz, T instance) {
			this.clazz = clazz;
			this.instance = instance;
		}

		public ProxyBuilder overwrite(String methodName, Object value) {
			substitutes.put(methodName, value);

			return this;
		}

		public T create() {
			InvocationHandler invocationHandler = new InvocationHandler() {
				@Override
				public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
					Object substitute = substitutes.get(method.getName());
					if (substitute != null) {
						return substitute;
					}
					return method.invoke(instance, args);
				}
			};
			return ProxyCreator.create(clazz, invocationHandler);
		}
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy