下面列出了java.lang.reflect.InvocationTargetException#getCause ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Test
public void voidResultWithParamAppCtxLocal() throws Exception {
prepare("VoidResultWithParam");
m = method(int.class, String.class);
//ctx.saveLocal();
try {
m.invoke(c, 100, "foo");
fail("Result expected to be thrown out");
} catch (InvocationTargetException e) {
if (e.getCause() instanceof Result) {
// success
eq(100, ctx.renderArg("foo"));
eq("foo", ctx.renderArg("bar"));
return;
}
throw e;
}
}
/** Run all test cases. */
void run() throws Exception {
initTestClasses();
for (Method m: getClass().getDeclaredMethods()) {
Annotation a = m.getAnnotation(Test.class);
if (a != null) {
System.err.println(m.getName());
try {
m.invoke(this, new Object[] { });
} catch (InvocationTargetException e) {
Throwable cause = e.getCause();
throw (cause instanceof Exception) ? ((Exception) cause) : e;
}
System.err.println();
}
}
if (errors > 0)
throw new Exception(errors + " errors occurred");
}
/**
* Run all methods annotated with @Test, and throw an exception if any
* errors are reported..
* Typically called on a tester object in main()
* @throws Exception if any errors occurred
*/
void runTests() throws Exception {
for (Method m: getClass().getDeclaredMethods()) {
Annotation a = m.getAnnotation(Test.class);
if (a != null) {
try {
out.println("Running test " + m.getName());
m.invoke(this);
} catch (InvocationTargetException e) {
Throwable cause = e.getCause();
throw (cause instanceof Exception) ? ((Exception) cause) : e;
}
out.println();
}
}
if (errors > 0)
throw new Exception(errors + " errors occurred");
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (method.getName().equals("onWindowFocusChanged") && args.length == 1
&& args[0] instanceof Boolean) {
onWindowFocusChanged((boolean) args[0]);
return null;
} else {
try {
return method.invoke(mCallback, args);
} catch (InvocationTargetException e) {
// Special-case for when a method is not defined on the underlying
// Window.Callback object. Because we're using a Proxy to forward all method
// calls, this breaks the Android framework's handling for apps built against
// an older SDK. The framework expects an AbstractMethodError but due to
// reflection it becomes wrapped inside an InvocationTargetException. Undo the
// wrapping to signal the framework accordingly.
if (e.getCause() instanceof AbstractMethodError) {
throw e.getCause();
}
throw e;
}
}
}
public static Object invoke(Method m, Object obj, Object[] params)
throws InvocationTargetException, IllegalAccessException {
try {
return bounce.invoke(null, m, obj, params);
} catch (InvocationTargetException ie) {
Throwable t = ie.getCause();
if (t instanceof InvocationTargetException) {
throw (InvocationTargetException) t;
} else if (t instanceof IllegalAccessException) {
throw (IllegalAccessException) t;
} else if (t instanceof RuntimeException) {
throw (RuntimeException) t;
} else if (t instanceof Error) {
throw (Error) t;
} else {
throw new Error("Unexpected invocation error", t);
}
} catch (IllegalAccessException iae) {
// this can't happen
throw new Error("Unexpected invocation error", iae);
}
}
/**
* Get a class's set of tests from its suite method through reflection.
*/
private static Test addSuiteByReflection(String className) throws Exception
{
try {
Class clz = Class.forName(className);
Method sm = clz.getMethod("suite", null);
return (Test) sm.invoke(null, null);
} catch (LinkageError e) {
return new TestSuite("SKIPPED: " + className + " - " +
e.getMessage());
} catch (InvocationTargetException ite) {
Throwable cause = ite.getCause();
if (cause instanceof LinkageError) {
return new TestSuite("SKIPPED: " + className + " - " +
cause.getMessage());
} else {
throw ite;
}
} catch (ClassNotFoundException ce) { // Do not add a suite not built.
return new TestSuite("SKIPPED: Class not found: " + className +
" - " + ce.getMessage());
}
}
@Test
public void testValidateInjectSpec_Option() throws Exception {
Class<?> reflection = Class.forName("picocli.CommandLine$Model$CommandReflection");
Method validateInjectSpec = reflection.getDeclaredMethod("validateInjectSpec", CommandLine.Model.TypedMember.class);
validateInjectSpec.setAccessible(true);
CommandLine.Model.TypedMember typedMember = new CommandLine.Model.TypedMember(ValidateInjectSpec.class.getDeclaredField("x"));
try {
validateInjectSpec.invoke(null, typedMember);
fail("expected Exception");
} catch (InvocationTargetException ite) {
CommandLine.DuplicateOptionAnnotationsException ex = (CommandLine.DuplicateOptionAnnotationsException) ite.getCause();
assertEquals("A member cannot have both @Spec and @Option annotations, but 'int picocli.ModelCommandReflectionTest$ValidateInjectSpec.x' has both.", ex.getMessage());
}
}
/**
* This is the general test of most methods in the
* {@link RealVector#unmodifiableRealVector(RealVector) unmodifiable vector}.
* It works as follows.
* First, an unmodifiable view of a copy of the specified random vector
* {@code u} is created: this defines {@code v}. Then the <em>same</em>
* method {@code m} is invoked on {@code u} and {@code v}, with randomly
* generated parameters {@code args}.
* If it turns out that {@code u} has changed after the call of method
* {@code m}, then this test checks that the call of this method on
* {@code v} resulted in a {@link MathUnsupportedOperationException}. If
* {@code u} was not modified, then this test checks that the results
* returned by the call of method {@code m} on {@code u} and {@code v}
* returned the same result.
*
* @param m Method to be tested.
* @param u Random vector from which the unmodifiable view is to be
*constructed.
* @param args Arguments to be passed to method {@code m}.
*/
private void callMethod(final Method m,
final RealVector u,
final Object... args)
throws IllegalAccessException,
IllegalArgumentException,
InvocationTargetException {
final RealVector uu = u.copy();
final RealVector v = RealVector.unmodifiableRealVector(u.copy());
Object exp = m.invoke(u, args);
if (equals(uu, u)) {
Object act = m.invoke(v, args);
Assert.assertTrue(m.toGenericString() + ", unmodifiable vector has changed",
equals(uu, v));
Assert.assertTrue(m.toGenericString() + ", wrong result",
equals(exp, act));
} else {
boolean flag = false;
try {
m.invoke(v, args);
} catch (InvocationTargetException e) {
if (e.getCause() instanceof MathUnsupportedOperationException) {
flag = true;
}
}
Assert.assertTrue(m.toGenericString()+", exception should have been thrown", flag);
}
}
protected Object callRead(final Object instance, final byte[] array) throws Exception {
try {
return this.callRead(instance, new JBBPBitInputStream(new ByteArrayInputStream(array)));
} catch (InvocationTargetException ex) {
if (ex.getCause() != null) {
throw (Exception) ex.getCause();
} else {
throw ex;
}
}
}
protected Object invokeMethod(Method method, Object[] args) throws Throwable {
try {
if (!method.isAccessible()) {
method.setAccessible(true);
}
return method.invoke(currentProxy.proxy, args);
} catch (InvocationTargetException e) {
throw e.getCause();
}
}
/**
* Invokes java.beans.BeanInfo.getPropertyDescriptors()
*/
static Object[] getPropertyDescriptors(Object bi) {
try {
return (Object[])getPropertyDescriptors.invoke(bi);
} catch (InvocationTargetException e) {
Throwable cause = e.getCause();
if (cause instanceof RuntimeException)
throw (RuntimeException)cause;
throw new AssertionError(e);
} catch (IllegalAccessException iae) {
throw new AssertionError(iae);
}
}
static ResourceRecord parse(String data, int offset, boolean qSection)
throws Throwable {
byte[] bytes = data.getBytes(ISO_8859_1);
try {
return rrConstructor.newInstance(
bytes, bytes.length, offset, qSection, !qSection);
} catch (InvocationTargetException e) {
throw e.getCause();
}
}
/** Combo test to run all test cases in all modes. */
void run() throws Exception {
javac = JavacTool.create();
fm = javac.getStandardFileManager(null, null, null);
try {
for (RunKind rk: RunKind.values()) {
for (GenKind gk: GenKind.values()) {
for (Method m: getClass().getDeclaredMethods()) {
Annotation a = m.getAnnotation(Test.class);
if (a != null) {
init(rk, gk, m.getName());
try {
m.invoke(this, new Object[] { rk, gk });
} catch (InvocationTargetException e) {
Throwable cause = e.getCause();
throw (cause instanceof Exception) ? ((Exception) cause) : e;
}
System.err.println();
}
}
}
}
System.err.println(testCount + " tests" + ((errorCount == 0) ? "" : ", " + errorCount + " errors"));
if (errorCount > 0)
throw new Exception(errorCount + " errors found");
} finally {
fm.close();
}
}
@Test(expectedExceptions=NullPointerException.class)
public void constructor_nullTime() throws Throwable {
Constructor<OffsetDateTime> con = OffsetDateTime.class.getDeclaredConstructor(LocalDateTime.class, ZoneOffset.class);
con.setAccessible(true);
try {
con.newInstance(null, OFFSET_PONE);
} catch (InvocationTargetException ex) {
throw ex.getCause();
}
}
/**
* Invokes java.beans.BeanInfo.getPropertyDescriptors()
*/
static Object[] getPropertyDescriptors(Object bi) {
try {
return (Object[])getPropertyDescriptors.invoke(bi);
} catch (InvocationTargetException e) {
Throwable cause = e.getCause();
if (cause instanceof RuntimeException)
throw (RuntimeException)cause;
throw new AssertionError(e);
} catch (IllegalAccessException iae) {
throw new AssertionError(iae);
}
}
@Test(expected = UnsupportedOperationException.class)
public void testConstructorThrowsException() throws Exception {
Constructor<?> constructor = ByteBuddyAgent.class.getDeclaredConstructor();
constructor.setAccessible(true);
try {
constructor.newInstance();
fail();
} catch (InvocationTargetException exception) {
throw (Exception) exception.getCause();
}
}
/**
* Invokes java.beans.PropertyDescriptor.getReadMethod()
*/
static Method getReadMethod(Object pd) {
try {
return (Method)getReadMethod.invoke(pd);
} catch (InvocationTargetException e) {
Throwable cause = e.getCause();
if (cause instanceof RuntimeException)
throw (RuntimeException)cause;
throw new AssertionError(e);
} catch (IllegalAccessException iae) {
throw new AssertionError(iae);
}
}
/**
* Constructs an instance of selected <code>Runner</code> child class.
* <p/>
* @param srv Target Payara server.
* @param cmd Payara server administration command entity.
* @param runnerClass Class of newly instantiated <code>runner</code>
* @return Payara server administration command execution object.
* @throws <code>CommandException</code> if construction of new instance
* fails.
*/
Runner newRunner(final PayaraServer srv, final Command cmd,
final Class runnerClass) throws CommandException {
final String METHOD = "newRunner";
Constructor<Runner> con = null;
Runner runner = null;
try {
con = runnerClass.getConstructor(PayaraServer.class, Command.class);
} catch (NoSuchMethodException | SecurityException nsme) {
throw new CommandException(CommandException.RUNNER_INIT, nsme);
}
if (con == null) {
return runner;
}
try {
runner = con.newInstance(srv, cmd);
} catch (InstantiationException | IllegalAccessException ie) {
throw new CommandException(CommandException.RUNNER_INIT, ie);
} catch (InvocationTargetException ite) {
LOGGER.log(Level.WARNING, "exceptionMsg", ite.getMessage());
Throwable t = ite.getCause();
if (t != null) {
LOGGER.log(Level.WARNING, "cause", t.getMessage());
}
throw new CommandException(CommandException.RUNNER_INIT, ite);
}
return runner;
}
@Override
public void run(final TaskMonitor monitor) {
final MessageLog log = new MessageLog();
AnalysisWorker worker = new AnalysisWorker() {
@Override
public String getWorkerName() {
return "Load PDB";
}
@Override
public boolean analysisWorkerCallback(Program currentProgram, Object workerContext,
TaskMonitor currentMonitor) throws Exception, CancelledException, PdbException {
PdbParser parser =
new PdbParser(pdbFile, program, service, true, currentMonitor);
parser.parse();
parser.openDataTypeArchives();
parser.applyTo(log);
analyzeSymbols(currentMonitor, log);
return !monitor.isCancelled();
}
};
boolean analyzed =
program.getOptions(Program.PROGRAM_INFO).getBoolean(Program.ANALYZED, false);
if (analyzed) {
Msg.showWarn(this, null, "PDB Warning",
"Loading PDB after analysis has been performed will produce" +
"\npoor results. PDBs should be loaded prior to analysis or" +
"\nautomatically during auto-analysis.");
}
try {
AutoAnalysisManager.getAnalysisManager(program)
.scheduleWorker(worker, null, true,
monitor);
}
catch (InterruptedException | CancelledException e1) {
// ignore
}
catch (InvocationTargetException e) {
String message;
Throwable t = e.getCause();
if (t == null) {
message = "Unknown cause";
}
else {
message = t.getMessage();
if (message == null) {
message = t.toString();
}
}
Msg.showError(getClass(), null, "Load PDB Failed", message, t);
}
if (log.getMsgCount() > 0) {
MultiLineMessageDialog dialog = new MultiLineMessageDialog("Load PDB File",
"There were warnings/errors loading the PDB file.", log.toString(),
MultiLineMessageDialog.WARNING_MESSAGE, false);
DockingWindowManager.showDialog(null, dialog);
}
}
private static void runTests(
Callable<MBeanServerConnection> maker, Runnable breaker)
throws Exception {
for (Method m : OldMBeanServerTest.class.getDeclaredMethods()) {
if (Modifier.isStatic(m.getModifiers()) &&
m.getName().startsWith("test") &&
m.getParameterTypes().length == 0) {
ExpectException expexc = m.getAnnotation(ExpectException.class);
mbsc = maker.call();
try {
m.invoke(null);
if (expexc != null) {
failure =
m.getName() + " did not got expected exception " +
expexc.value().getName();
System.out.println(failure);
} else
System.out.println(m.getName() + " OK");
} catch (InvocationTargetException ite) {
Throwable t = ite.getCause();
String prob = null;
if (expexc != null) {
if (expexc.value().isInstance(t)) {
System.out.println(m.getName() + " OK (got expected " +
expexc.value().getName() + ")");
} else
prob = "got wrong exception";
} else
prob = "got exception";
if (prob != null) {
failure = m.getName() + ": " + prob + " " +
t.getClass().getName();
System.out.println(failure);
t.printStackTrace(System.out);
}
} finally {
if (breaker != null)
breaker.run();
}
}
}
}