1/* 2 * Copyright (c) 2007 Mockito contributors 3 * This program is made available under the terms of the MIT License. 4 */ 5package org.mockito.internal.invocation; 6 7import java.io.Serializable; 8import java.lang.reflect.Method; 9import java.util.Arrays; 10 11import org.mockito.exceptions.base.MockitoException; 12 13public class SerializableMethod implements Serializable, MockitoMethod { 14 15 private static final long serialVersionUID = 6005610965006048445L; 16 17 private Class<?> declaringClass; 18 private String methodName; 19 private Class<?>[] parameterTypes; 20 private Class<?> returnType; 21 private Class<?>[] exceptionTypes; 22 private boolean isVarArgs; 23 24 public SerializableMethod(Method method) { 25 declaringClass = method.getDeclaringClass(); 26 methodName = method.getName(); 27 parameterTypes = method.getParameterTypes(); 28 returnType = method.getReturnType(); 29 exceptionTypes = method.getExceptionTypes(); 30 isVarArgs = method.isVarArgs(); 31 } 32 33 public String getName() { 34 return methodName; 35 } 36 37 public Class<?> getReturnType() { 38 return returnType; 39 } 40 41 public Class<?>[] getParameterTypes() { 42 return parameterTypes; 43 } 44 45 public Class<?>[] getExceptionTypes() { 46 return exceptionTypes; 47 } 48 49 public boolean isVarArgs() { 50 return isVarArgs; 51 } 52 53 public Method getJavaMethod() { 54 try { 55 return declaringClass.getDeclaredMethod(methodName, parameterTypes); 56 } catch (SecurityException e) { 57 String message = String.format( 58 "The method %1$s.%2$s is probably private or protected and cannot be mocked.\n" + 59 "Please report this as a defect with an example of how to reproduce it.", declaringClass, methodName); 60 throw new MockitoException(message, e); 61 } catch (NoSuchMethodException e) { 62 String message = String.format( 63 "The method %1$s.%2$s does not exists and you should not get to this point.\n" + 64 "Please report this as a defect with an example of how to reproduce it.", declaringClass, methodName); 65 throw new MockitoException(message, e); 66 } 67 } 68 69 @Override 70 public int hashCode() { 71 return 1; 72 } 73 74 @Override 75 public boolean equals(Object obj) { 76 if (this == obj) 77 return true; 78 if (obj == null) 79 return false; 80 if (getClass() != obj.getClass()) 81 return false; 82 SerializableMethod other = (SerializableMethod) obj; 83 if (declaringClass == null) { 84 if (other.declaringClass != null) 85 return false; 86 } else if (!declaringClass.equals(other.declaringClass)) 87 return false; 88 if (methodName == null) { 89 if (other.methodName != null) 90 return false; 91 } else if (!methodName.equals(other.methodName)) 92 return false; 93 if (!Arrays.equals(parameterTypes, other.parameterTypes)) 94 return false; 95 if (returnType == null) { 96 if (other.returnType != null) 97 return false; 98 } else if (!returnType.equals(other.returnType)) 99 return false; 100 return true; 101 } 102} 103