001package ball.lang;
002/*-
003 * ##########################################################################
004 * Utilities
005 * %%
006 * Copyright (C) 2008 - 2022 Allen D. Ball
007 * %%
008 * Licensed under the Apache License, Version 2.0 (the "License");
009 * you may not use this file except in compliance with the License.
010 * You may obtain a copy of the License at
011 *
012 *      http://www.apache.org/licenses/LICENSE-2.0
013 *
014 * Unless required by applicable law or agreed to in writing, software
015 * distributed under the License is distributed on an "AS IS" BASIS,
016 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
017 * See the License for the specific language governing permissions and
018 * limitations under the License.
019 * ##########################################################################
020 */
021import java.util.Collections;
022import java.util.HashMap;
023import java.util.Map;
024
025/**
026 * Provides mapping of Java primitive {@link Class}es to their "wrapper"
027 * {@link Class}es.
028 *
029 * @author {@link.uri mailto:ball@hcf.dev Allen D. Ball}
030 */
031public class PrimitiveTypeMap extends HashMap<Class<?>,Class<?>> {
032    private static final long serialVersionUID = 542657344546950531L;
033
034    /**
035     * Unmodifiable instance of a {@link PrimitiveTypeMap}.
036     */
037    public static final Map<Class<?>,Class<?>> INSTANCE = Collections.unmodifiableMap(new PrimitiveTypeMap());
038
039    /**
040     * Sole constructor.
041     */
042    public PrimitiveTypeMap() {
043        super();
044
045        put(Boolean.TYPE, Boolean.class);
046        put(Byte.TYPE, Byte.class);
047        put(Character.TYPE, Character.class);
048        put(Double.TYPE, Double.class);
049        put(Float.TYPE, Float.class);
050        put(Integer.TYPE, Integer.class);
051        put(Long.TYPE, Long.class);
052        put(Short.TYPE, Short.class);
053        put(Void.TYPE, Void.class);
054    }
055
056    /**
057     * Static method to get the "boxed" {@link Class} for a Java primitive
058     * {@link Class}.
059     *
060     * @param   type            The {@link Class}.
061     *
062     * @return  The "boxed" {@link Class} if the argument {@link Class} is a
063     *          primitive type; the argument otherwise.
064     */
065    public static Class<?> asBoxedType(Class<?> type) {
066        return (type != null && type.isPrimitive()) ? INSTANCE.get(type) : type;
067    }
068}