OpenConcerto

Dépôt officiel du code source de l'ERP OpenConcerto
sonarqube

svn://code.openconcerto.org/openconcerto

Rev

Rev 144 | Go to most recent revision | Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
17 ilm 1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
4
 * Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
5
 *
6
 * The contents of this file are subject to the terms of the GNU General Public License Version 3
7
 * only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
8
 * copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
9
 * language governing permissions and limitations under the License.
10
 *
11
 * When distributing the software, include this License Header Notice in each file.
12
 */
13
 
14
 package org.openconcerto.utils;
15
 
16
import java.lang.reflect.Array;
17
import java.lang.reflect.GenericArrayType;
18
import java.lang.reflect.ParameterizedType;
19
import java.lang.reflect.Type;
20
import java.lang.reflect.TypeVariable;
21
import java.util.ArrayList;
22
import java.util.Arrays;
23
import java.util.HashMap;
24
import java.util.LinkedHashMap;
25
import java.util.List;
26
import java.util.Map;
27
 
28
public final class ReflectUtils {
29
 
30
    static private Map<Type, Type> resolveTypes(Class<?> c, Class<?> raw) {
31
        final Map<Type, Type> res = new HashMap<Type, Type>();
32
        if (!raw.isAssignableFrom(c))
33
            return res;
34
 
35
        // c : ListDeString implements List<String>
36
        final List<Type> types = new ArrayList<Type>(Arrays.asList(c.getGenericInterfaces()));
37
        types.add(c.getGenericSuperclass());
38
        for (final Type t : types) {
39
            if (t instanceof ParameterizedType) {
40
                // eg List<String>
41
                final ParameterizedType pt = (ParameterizedType) t;
42
                if (raw.isAssignableFrom((Class) pt.getRawType())) {
43
                    // eg List.class (List<E>)
44
                    final Class<?> rawType = (Class) pt.getRawType();
45
                    // eg [String.class]
46
                    final Type[] actualTypeArguments = pt.getActualTypeArguments();
47
                    // eg [E]
48
                    final TypeVariable<?>[] typeParameters = rawType.getTypeParameters();
49
                    for (int i = 0; i < actualTypeArguments.length; i++) {
50
                        res.put(typeParameters[i], actualTypeArguments[i]);
51
                    }
52
                }
53
            }
54
            final Class<?> tc = getClass(t);
55
            if (tc != null) {
56
                res.putAll(resolveTypes(tc, raw));
57
            }
58
        }
59
        return res;
60
    }
61
 
62
    /**
63
     * The map of type arguments of baseClass to actual type for childClass.
64
     *
65
     * @param <T> the type of the baseClass.
66
     * @param childClass the class to test, eg Props.class with Props<V> extends Map<String, V>.
67
     * @param baseClass the generic superclass, eg Map.class.
68
     * @return a the map, eg {K => String.class, V => null}.
69
     */
70
    public static <T> Map<TypeVariable<Class<T>>, Class<?>> getTypeArgumentsMap(Class<? extends T> childClass, Class<T> baseClass) {
71
        final TypeVariable<Class<T>>[] actualTypeArguments = baseClass.getTypeParameters();
72
        if (actualTypeArguments.length == 0)
73
            throw new IllegalArgumentException(baseClass + " is not generic");
74
 
75
        final Map<TypeVariable<Class<T>>, Class<?>> res = new LinkedHashMap<TypeVariable<Class<T>>, Class<?>>();
76
        final Map<Type, Type> resolvedTypes = resolveTypes(childClass, baseClass);
77
        // for each actual type argument provided to baseClass, determine (if possible)
78
        // the raw class for that type argument.
79
        // resolve types by chasing down type variables.
80
        for (final TypeVariable<Class<T>> baseType : actualTypeArguments) {
81
            Type currentType = baseType;
82
            while (resolvedTypes.containsKey(currentType)) {
83
                currentType = resolvedTypes.get(currentType);
84
            }
85
            res.put(baseType, getClass(currentType));
86
        }
87
 
88
        return res;
89
    }
90
 
91
    /**
92
     * Search for the list of class used to extend/implement a generic class/interface.
93
     *
94
     * @param <T> the type of the baseClass.
95
     * @param childClass the class to test, eg Props.class with Props<V> extends Map<String, V>.
96
     * @param baseClass the generic superclass, eg Map.class.
97
     * @return the list of actual classes w/o the possible nulls (if childClass is generic), never
98
     *         <code>null</code>, eg [Boolean.class].
99
     */
100
    public static <T> List<Class<?>> getTypeArguments(Class<? extends T> childClass, Class<T> baseClass) {
101
        final ArrayList<Class<?>> res = new ArrayList<Class<?>>();
102
        // ok since getTypeArgumentsMap returns a LinkedHashMap
103
        for (final Class<?> c : getTypeArgumentsMap(childClass, baseClass).values()) {
104
            if (c != null)
105
                res.add(c);
106
        }
107
        return res;
108
    }
109
 
110
    static public <U> List<Class<?>> getTypeArguments(U o, Class<U> raw) {
111
        return getTypeArguments(o.getClass().asSubclass(raw), raw);
112
    }
113
 
114
    /**
115
     * Whether o can be casted to raw&lt;typeArgs&gt;.
116
     *
117
     * @param <U> type of the superclass.
118
     * @param o the instance to check, eg new MapOfInt2Boolean().
119
     * @param raw the generic superclass, eg Map.class.
120
     * @param typeArgs arguments to <code>raw</code>, eg Integer.class, Boolean.class.
121
     * @return whether o is a raw&lt;typeArgs&gt;, eg <code>true</code> : new MapOfInt2Boolean()
122
     *         is a Map&lt;Integer, Boolean&gt;.
123
     */
124
    static public <U> boolean isCastable(U o, Class<U> raw, Class... typeArgs) {
125
        return getTypeArguments(o, raw).equals(Arrays.asList(typeArgs));
126
    }
127
 
128
    // *** pasted from http://www.artima.com/weblogs/viewpost.jsp?thread=208860
129
 
130
    /**
131
     * Get the underlying class for a type, or null if the type is a variable type.
132
     *
133
     * @param type the type
134
     * @return the underlying class
135
     */
136
    private static Class<?> getClass(Type type) {
137
        if (type instanceof Class) {
138
            return (Class) type;
139
        } else if (type instanceof ParameterizedType) {
140
            return getClass(((ParameterizedType) type).getRawType());
141
        } else if (type instanceof GenericArrayType) {
142
            Type componentType = ((GenericArrayType) type).getGenericComponentType();
143
            Class<?> componentClass = getClass(componentType);
144
            if (componentClass != null) {
145
                return Array.newInstance(componentClass, 0).getClass();
146
            } else {
147
                return null;
148
            }
149
        } else {
150
            return null;
151
        }
152
    }
153
 
154
}