1 package complexlib; 2 3 import java.io.PrintWriter; 4 import java.lang.reflect.Method; 5 6 /** 7 * Invoke a method of a class in an own thread. Provide a method to end 8 * the thread. 9 */ 10 public class MethodThread extends Thread 11 { 12 13 /** The method that should be executed **/ 14 private Method mTestMethod = null; 15 /** The object that implements the method **/ 16 private Object mInvokeClass = null; 17 /** A PrintWriter for debug Output **/ 18 private PrintWriter mLog = null; 19 /** An Error String **/ 20 private String mErrMessage = null; 21 /** Did an Exception happen? **/ 22 private boolean mExceptionHappened = false; 23 private Object[] mParameter = null; 24 25 /** 26 * Constructor. 27 * @param testMethod The method that will be invoked. 28 * @param invokeClass The class where the method is invoked. 29 * @param log The logging mechanism. 30 */ 31 public MethodThread(Method testMethod, Object invokeClass, PrintWriter log) 32 { 33 mTestMethod = testMethod; 34 mInvokeClass = invokeClass; 35 mLog = log; 36 } 37 38 public MethodThread(Method testMethod, Object invokeClass, Object[] parameter, PrintWriter log) 39 { 40 mTestMethod = testMethod; 41 mInvokeClass = invokeClass; 42 mParameter = parameter; 43 mLog = log; 44 } 45 46 /** 47 * Invoke the method. 48 */ 49 public void run() 50 { 51 try 52 { 53 mTestMethod.invoke(mInvokeClass, mParameter); 54 } 55 catch (IllegalAccessException e) 56 { 57 e.printStackTrace(mLog); 58 mErrMessage = e.getMessage(); 59 mExceptionHappened = true; 60 } 61 catch (java.lang.reflect.InvocationTargetException e) 62 { 63 Throwable t = e.getTargetException(); 64 if (!(t instanceof ComplexTestCase.AssureException)) 65 { 66 t.printStackTrace(mLog); 67 mErrMessage = t.getMessage(); 68 if (mErrMessage == null) 69 { 70 mErrMessage = t.toString(); 71 } 72 mExceptionHappened = true; 73 } 74 75 } 76 } 77 78 /** 79 * Get the error message 80 * @return The error message. 81 */ 82 public String getErrorMessage() 83 { 84 return mErrMessage; 85 } 86 87 /** 88 * Is there an error message? 89 * @return True, if an error did happen. 90 */ 91 public boolean hasErrorMessage() 92 { 93 return mExceptionHappened; 94 } 95 96 /** 97 * Stop the running method. 98 */ 99 public void destroy() 100 { 101 try 102 { 103 interrupt(); 104 } 105 catch (SecurityException e) 106 { 107 e.printStackTrace(mLog); 108 mErrMessage = e.getMessage(); 109 mExceptionHappened = true; 110 } 111 } 112 } 113