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

net.openhft.chronicle.testframework.internal.DelegationBuilder Maven / Gradle / Ivy

There is a newer version: 2.27ea0
Show newest version
package net.openhft.chronicle.testframework.internal;

import net.openhft.chronicle.testframework.Delegation;
import org.jetbrains.annotations.NotNull;

import java.lang.reflect.Proxy;
import java.util.Objects;
import java.util.function.Function;

import static java.util.Objects.requireNonNull;

public final class DelegationBuilder implements Delegation.Builder {

    private final D delegate;
    @SuppressWarnings("unchecked")
    private Class type = (Class) Object.class;
    private Function toStringFunction = Objects::toString;

    public DelegationBuilder(@NotNull final D delegate) {
        this.delegate = requireNonNull(delegate);
    }

    @Override
    public  Delegation.Builder as(@NotNull final Class type) {
        requireNonNull(type);
        @SuppressWarnings("unchecked") final DelegationBuilder newTypeBuilder = (DelegationBuilder) this;
        newTypeBuilder.type = type;
        return newTypeBuilder;
    }

    @Override
    public Delegation.Builder toStringFunction(Function toStringFunction) {
        this.toStringFunction = requireNonNull(toStringFunction);
        return this;
    }

    @SuppressWarnings("unchecked")
    @Override
    public T build() {
        return (T) Proxy.newProxyInstance(
                type.getClassLoader(),
                new Class[]{type}, (proxy1, method, args) -> {
                    if ("toString".equals(method.getName()) && args == null) {
                        return toStringFunction.apply(delegate);
                    }
                    return method.invoke(delegate, args);
                });
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy