How to use method of org.easymock.internal.ReflectionUtils class

Best Easymock code snippet using org.easymock.internal.ReflectionUtils.

Run Easymock automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

copy
1/**
2 * Copyright 2001-2013 the original author or authors.
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.easymock.internal;
17
18import java.lang.reflect.Constructor;
19import java.lang.reflect.Method;
20import java.lang.reflect.Modifier;
21import java.util.Arrays;
22import java.util.HashMap;
23import java.util.Map;
24
25/**
26 * @author Henri Tremblay
27 */
28public final class ReflectionUtils {
29
30    private static Map<Class<?>, Class<?>> primitiveToWrapperType = new HashMap<Class<?>, Class<?>>();
31
32    static {
33        primitiveToWrapperType.put(boolean.class, Boolean.class);
34        primitiveToWrapperType.put(byte.class, Byte.class);
35        primitiveToWrapperType.put(short.class, Short.class);
36        primitiveToWrapperType.put(char.class, Character.class);
37        primitiveToWrapperType.put(int.class, Integer.class);
38        primitiveToWrapperType.put(long.class, Long.class);
39        primitiveToWrapperType.put(float.class, Float.class);
40        primitiveToWrapperType.put(double.class, Double.class);
41    }
42
43    public static final Method OBJECT_EQUALS = getDeclaredMethod(Object.class, "equals",
44            new Class[] { Object.class });
45
46    public static final Method OBJECT_HASHCODE = getDeclaredMethod(Object.class, "hashCode", (Class[]) null);
47
48    public static final Method OBJECT_TOSTRING = getDeclaredMethod(Object.class, "toString", (Class[]) null);
49
50    public static final Method OBJECT_FINALIZE = getDeclaredMethod(Object.class, "finalize", (Class[]) null);
51
52    // ///CLOVER:OFF
53    private ReflectionUtils() {
54    }
55
56    // ///CLOVER:ON
57
58    /**
59     * Attempt to find a {@link Method} on the supplied class with the supplied
60     * name and no parameters. Searches all superclasses up to
61     * <code>Object</code>.
62     * <p>
63     * Returns <code>null</code> if no {@link Method} can be found.
64     * 
65     * @param clazz
66     *            the class to introspect
67     * @param name
68     *            the name of the method
69     * @return the Method object, or <code>null</code> if none found
70     */
71    public static Method findMethod(final Class<?> clazz, final String name) {
72        return findMethod(clazz, name, (Class<?>[]) null);
73    }
74
75    /**
76     * Attempt to find a {@link Method} on the supplied class with the supplied
77     * name and parameter types. Searches all superclasses up to
78     * <code>Object</code>.
79     * <p>
80     * Returns <code>null</code> if no {@link Method} can be found.
81     * 
82     * @param clazz
83     *            the class to introspect
84     * @param name
85     *            the name of the method
86     * @param paramTypes
87     *            the parameter types of the method (may be <code>null</code> to
88     *            indicate any signature)
89     * @return the Method object, or <code>null</code> if none found
90     */
91    public static Method findMethod(final Class<?> clazz, final String name, final Class<?>... paramTypes) {
92        Class<?> searchType = clazz;
93        while (searchType != null) {
94            final Method[] methods = searchType.getDeclaredMethods();
95            Method result = null;
96            for (final Method method : methods) {
97                // Private methods can't be mocked so just skip them
98                if (Modifier.isPrivate(method.getModifiers())) {
99                    continue;
100                }
101                // Skip bridges because we never mock them. We mock the method underneath
102                if (method.isBridge()) {
103                    continue;
104                }
105                if (name.equals(method.getName())) {
106                    if (paramTypes == null) {
107                        if (result != null) {
108                            throw new RuntimeException("Ambiguous name: More than one method are named "
109                                    + name);
110                        }
111                        result = method;
112                    } else if (Arrays.equals(paramTypes, method.getParameterTypes())) {
113                        return method;
114                    }
115                }
116            }
117            if (result != null) {
118                return result;
119            }
120            searchType = searchType.getSuperclass();
121        }
122        return null;
123    }
124
125    /**
126     * Returns a constructor that contains {@code objs} as arguments.
127     * 
128     * <p>
129     * We could not do something like {@code clazz.getConstructor(objs.class())}
130     * because that would require casting all the passed arguments to the exact
131     * parameter types of the desired constructor.
132     * 
133     * @param clazz
134     *            class on which we are searching the constructor
135     * @param <T>
136     *            type of the class searched
137     * @param objs
138     *            list of arguments of the constructor
139     * @return a constructor with the arguments in {@code objs}
140     * @throws NoSuchMethodException
141     *             when the constructor with {@code args} does not exist or is
142     *             ambiguous
143     */
144    @SuppressWarnings("unchecked")
145    public static <T> Constructor<T> getConstructor(final Class<T> clazz, final Object... objs)
146            throws NoSuchMethodException {
147        Constructor<T> ret = null;
148        for (final Constructor<?> classConstructor : clazz.getDeclaredConstructors()) {
149            if (isMatchingConstructor(classConstructor, objs)) {
150                if (ret != null) {
151                    // We had already found a constructor, so this is ambiguous
152                    throw new IllegalArgumentException("Ambiguity in the constructors for " + clazz.getName()
153                            + ".");
154                }
155
156                // This unsafe cast is guaranteed to be correct by Class#getConstructors()
157                ret = (Constructor<T>) classConstructor;
158            }
159        }
160
161        if (ret != null) {
162            return ret;
163        }
164
165        // Not found
166        throw new NoSuchMethodException("Couldn't find constructor for class " + clazz.getName());
167    }
168
169    /**
170     * Returns true if objects in {@code objs} are eligible to be passed to
171     * {@code classConstructor}.
172     */
173    private static boolean isMatchingConstructor(final Constructor<?> classConstructor, final Object... objs) {
174
175        if (Modifier.isPrivate(classConstructor.getModifiers())) {
176            return false;
177        }
178
179        final Class<?>[] parameterTypes = classConstructor.getParameterTypes();
180        if (parameterTypes.length != objs.length) {
181            return false;
182        }
183
184        for (int i = 0; i < objs.length; ++i) {
185            Class<?> parameterType = parameterTypes[i];
186
187            // If the parameter is a primitive, we need to get the boxed equivalent type
188            if (parameterType.isPrimitive()) {
189                parameterType = wrapPrimitive(parameterType);
190            }
191
192            // Check if parameter type matches
193            if (!parameterType.isInstance(objs[i])) {
194                return false;
195            }
196        }
197
198        return true;
199    }
200
201    /**
202     * Given a primitive type, returns its boxed equivalent. For instance, given
203     * {@code int}, returns {@code Integer}.
204     * 
205     * @param parameterType
206     *            the primitive type
207     * @return the boxed equivalent
208     */
209    private static Class<?> wrapPrimitive(final Class<?> parameterType) {
210        return primitiveToWrapperType.get(parameterType);
211    }
212
213    /**
214     * Basically calls getDeclaredMethod on a Class but wraps the
215     * NoSuchMethodException into a Runtime.
216     * 
217     * @param clazz
218     *            class on which the getDeclaredMethod is called
219     * @param name
220     *            method name
221     * @param paramTypes
222     *            method parameters
223     * @return the method searched
224     */
225    public static Method getDeclaredMethod(final Class<?> clazz, final String name,
226            final Class<?>[] paramTypes) {
227        try {
228            return clazz.getDeclaredMethod(name, paramTypes);
229        } catch (final NoSuchMethodException e) {
230            throw new RuntimeException(e);
231        }
232    }
233}
234
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Trigger code on LambdaTest Cloud Grid

Execute automation tests with on a cloud-based Grid of 3000+ real browsers and operating systems for both web and mobile applications.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)