1/*
2 * Copyright 2003,2004 The Apache Software Foundation
3 *
4 *  Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 *  Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16package org.mockito.cglib.core;
17
18import java.util.Set;
19
20/**
21 * The default policy used by {@link AbstractClassGenerator}.
22 * Generates names such as
23 * <p><code>org.mockito.cglib.Foo$$EnhancerByCGLIB$$38272841</code><p>
24 * This is composed of a prefix based on the name of the superclass, a fixed
25 * string incorporating the CGLIB class responsible for generation, and a
26 * hashcode derived from the parameters used to create the object. If the same
27 * name has been previously been used in the same <code>ClassLoader</code>, a
28 * suffix is added to ensure uniqueness.
29 */
30public class DefaultNamingPolicy implements NamingPolicy {
31    public static final DefaultNamingPolicy INSTANCE = new DefaultNamingPolicy();
32
33    public String getClassName(String prefix, String source, Object key, Predicate names) {
34        if (prefix == null) {
35            prefix = "org.mockito.cglib.empty.Object";
36        } else if (prefix.startsWith("java")) {
37            prefix = "$" + prefix;
38        }
39        String base =
40            prefix + "$$" +
41            source.substring(source.lastIndexOf('.') + 1) +
42            getTag() + "$$" +
43            Integer.toHexString(key.hashCode());
44        String attempt = base;
45        int index = 2;
46        while (names.evaluate(attempt))
47            attempt = base + "_" + index++;
48        return attempt;
49    }
50
51    /**
52     * Returns a string which is incorporated into every generated class name.
53     * By default returns "ByCGLIB"
54     */
55    protected String getTag() {
56        return "ByCGLIB";
57    }
58}
59