001/*
002 * Copyright 2002-2020 the original author or authors.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *      https://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package org.springframework.cache.interceptor;
018
019import java.io.IOException;
020import java.io.ObjectInputStream;
021import java.io.Serializable;
022import java.util.Arrays;
023
024import org.springframework.lang.Nullable;
025import org.springframework.util.Assert;
026import org.springframework.util.StringUtils;
027
028/**
029 * A simple key as returned from the {@link SimpleKeyGenerator}.
030 *
031 * @author Phillip Webb
032 * @author Juergen Hoeller
033 * @since 4.0
034 * @see SimpleKeyGenerator
035 */
036@SuppressWarnings("serial")
037public class SimpleKey implements Serializable {
038
039        /**
040         * An empty key.
041         */
042        public static final SimpleKey EMPTY = new SimpleKey();
043
044
045        private final Object[] params;
046
047        // Effectively final, just re-calculated on deserialization
048        private transient int hashCode;
049
050
051        /**
052         * Create a new {@link SimpleKey} instance.
053         * @param elements the elements of the key
054         */
055        public SimpleKey(Object... elements) {
056                Assert.notNull(elements, "Elements must not be null");
057                this.params = elements.clone();
058                // Pre-calculate hashCode field
059                this.hashCode = Arrays.deepHashCode(this.params);
060        }
061
062
063        @Override
064        public boolean equals(@Nullable Object other) {
065                return (this == other ||
066                                (other instanceof SimpleKey && Arrays.deepEquals(this.params, ((SimpleKey) other).params)));
067        }
068
069        @Override
070        public final int hashCode() {
071                // Expose pre-calculated hashCode field
072                return this.hashCode;
073        }
074
075        @Override
076        public String toString() {
077                return getClass().getSimpleName() + " [" + StringUtils.arrayToCommaDelimitedString(this.params) + "]";
078        }
079
080        private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
081                ois.defaultReadObject();
082                // Re-calculate hashCode field on deserialization
083                this.hashCode = Arrays.deepHashCode(this.params);
084        }
085
086}