Bump odlparent to 5.0.0
[yangtools.git] / common / testutils / src / main / java / org / opendaylight / yangtools / testutils / mockito / MethodExtensions.java
1 /*
2  * Copyright (c) 2016 Red Hat, Inc. and others. All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.yangtools.testutils.mockito;
9
10 import java.lang.reflect.Method;
11 import java.lang.reflect.Parameter;
12 import java.lang.reflect.Type;
13 import java.util.regex.Pattern;
14 import org.checkerframework.checker.regex.qual.Regex;
15
16 /**
17  * Nicer shorter toString() for {@link Method} than it's default.
18  *
19  * <p>Without modifiers, return type, FQN of class and exceptions; instead with parameter names (if javac -parameters).
20  *
21  * @author Michael Vorburger
22  */
23 public final class MethodExtensions {
24     @Regex
25     private static final String PARAM_PATTERN_STR = "\\[\\]$";
26     private static final Pattern PARAM_PATTERN = Pattern.compile(PARAM_PATTERN_STR);
27
28     private MethodExtensions() {
29     }
30
31     public static String toString(final Method method) {
32         final StringBuilder sb = new StringBuilder();
33         sb.append(method.getName());
34
35         // copy/paste from java.lang.reflect.Executable.sharedToGenericString(int, boolean)
36         sb.append('(');
37         final Type[] params = method.getGenericParameterTypes();
38         // NEW
39         final Parameter[] parameters = method.getParameters();
40         for (int j = 0; j < params.length; j++) {
41             String param = params[j].getTypeName();
42             if (method.isVarArgs() && j == params.length - 1) {
43                 // replace T[] with T...
44                 param = PARAM_PATTERN.matcher(param).replaceFirst("...");
45             }
46             sb.append(param);
47             // NEW
48             if (parameters[j].isNamePresent()) {
49                 sb.append(' ');
50                 sb.append(parameters[j].getName());
51             }
52             // NEW END
53             if (j < params.length - 1) {
54                 // NEW ", " instead of ','
55                 sb.append(", ");
56             }
57         }
58         sb.append(')');
59
60         return sb.toString();
61     }
62
63 }