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

uk.ac.starlink.util.WrapUtils Maven / Gradle / Ivy

There is a newer version: 4.3
Show newest version
package uk.ac.starlink.util;

/**
 * Utilities relating to the {@link Wrapper} class.
 *
 * @author   Mark Taylor
 * @since    3 Apr 2008
 */
public class WrapUtils {

    /**
     * Private constructor prevents instantiation.
     */
    private WrapUtils() {
    }

    /**
     * Returns the object on which a given object is based.
     * If obj is a {@link Wrapper}, it is unwrapped as far
     * as possible and the base object is returned.
     * Otherwise obj itself is returned.
     *
     * @param  obj  test object
     * @return   ultimate base object of obj
     */
    public static Object getWrapped( Object obj ) {
        while ( obj instanceof Wrapper ) {
            obj = ((Wrapper) obj).getBase();
        }
        return obj;
    }

    /**
     * Attempts to return an object of a given class on which a given
     * object is based.
     * An object is unwrapped (see {@link Wrapper#getBase}) until an
     * object of class clazz is found, at which point it
     * is returned.  If no clazz object can be found,
     * null is returned.
     *
     * @param  obj   test object
     * @return   object within the wrapping hierarchy of class
     *           clazz, or null
     */
    public static Object getWrapped( Object obj, Class clazz ) {
        while ( true ) {
            if ( clazz.isAssignableFrom( obj.getClass() ) ) {
                return obj;
            }
            else if ( obj instanceof Wrapper ) {
                obj = ((Wrapper) obj).getBase();
            }
            else {
                return null;
            }
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy