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

io.permazen.util.CastFunction Maven / Gradle / Ivy

There is a newer version: 5.1.0
Show newest version

/*
 * Copyright (C) 2015 Archie L. Cobbs. All rights reserved.
 */

package io.permazen.util;

import com.google.common.base.Preconditions;

import java.util.function.Function;

/**
 * A {@link Function} that casts objects to some type.
 */
public class CastFunction implements Function {

    protected final Class type;

    /**
     * Constructor.
     *
     * @param type desired type
     * @throws IllegalArgumentException if {@code type} is null
     */
     public CastFunction(Class type) {
        Preconditions.checkArgument(type != null, "null type");
        this.type = type;
    }

    @Override
    public T apply(Object obj) {
        if (obj == null)
            return null;
        try {
            return this.type.cast(obj);
        } catch (ClassCastException e) {
            throw this.handleFailure(obj, e);
        }
    }

    public com.google.common.base.Function toGuava() {
        return this::apply;
    }

    /**
     * Generate an exception to throw when a cast failure occurs.
     *
     * 

* The implementation in {@link CastFunction} just throws {@code e}. * * @param obj object on which cast failed * @param e resulting exception * @return exception to throw */ protected RuntimeException handleFailure(Object obj, ClassCastException e) { return e; } }





© 2015 - 2025 Weber Informatics LLC | Privacy Policy