001 /*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements. See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License. You may obtain a copy of the License at
008 *
009 * http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017 package org.apache.commons.collections.map;
018
019 import java.util.Map;
020
021 import org.apache.commons.collections.functors.InstanceofPredicate;
022
023 /**
024 * Decorates another <code>Map</code> to validate that elements added
025 * are of a specific type.
026 * <p>
027 * The validation of additions is performed via an instanceof test against
028 * a specified <code>Class</code>. If an object cannot be added to the
029 * collection, an IllegalArgumentException is thrown.
030 * <p>
031 * <strong>Note that TypedMap is not synchronized and is not thread-safe.</strong>
032 * If you wish to use this map from multiple threads concurrently, you must use
033 * appropriate synchronization. The simplest approach is to wrap this map
034 * using {@link java.util.Collections#synchronizedMap(Map)}. This class may throw
035 * exceptions when accessed by concurrent threads without synchronization.
036 * <p>
037 * The returned implementation is Serializable from Commons Collections 3.1.
038 *
039 * @since Commons Collections 3.0
040 * @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $
041 *
042 * @author Stephen Colebourne
043 * @author Matthew Hawthorne
044 */
045 public class TypedMap {
046
047 /**
048 * Factory method to create a typed map.
049 * <p>
050 * If there are any elements already in the map being decorated, they
051 * are validated.
052 *
053 * @param map the map to decorate, must not be null
054 * @param keyType the type to allow as keys, must not be null
055 * @param valueType the type to allow as values, must not be null
056 * @throws IllegalArgumentException if list or type is null
057 * @throws IllegalArgumentException if the list contains invalid elements
058 */
059 public static Map decorate(Map map, Class keyType, Class valueType) {
060 return new PredicatedMap(
061 map,
062 InstanceofPredicate.getInstance(keyType),
063 InstanceofPredicate.getInstance(valueType)
064 );
065 }
066
067 /**
068 * Restrictive constructor.
069 */
070 protected TypedMap() {
071 }
072
073 }