下面列出了怎么用java.lang.reflect.InvocationTargetException的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Instantiate an object given a class name. Check that the
* <code>className</code> is a subclass of
* <code>superClass</code>. If that test fails or the object could
* not be instantiated, then <code>defaultValue</code> is returned.
*
* @param className The fully qualified class name of the object to instantiate.
* @param superClass The class to which the new object should belong.
* @param defaultValue The object to return in case of non-fulfillment
*/
public static Object instantiateByClassName(String className, Class<?> superClass,
Object defaultValue) {
if (className != null) {
try {
Object obj = LoaderUtil.newInstanceOf(className);
if (!superClass.isAssignableFrom(obj.getClass())) {
LOGGER.error("A \"{}\" object is not assignable to a \"{}\" variable", className,
superClass.getName());
return defaultValue;
}
return obj;
} catch (ClassNotFoundException | NoSuchMethodException | IllegalAccessException
| InstantiationException | InvocationTargetException e) {
LOGGER.error("Could not instantiate class [" + className + "].", e);
}
}
return defaultValue;
}
@Test
void messageCanBeCustomized() throws IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchMethodException {
for (final EdsdkError value : EdsdkError.values()) {
final Class<? extends EdsdkErrorException> aClass = value.getException().getClass();
if (aClass.equals(EdsdkErrorException.class)) {
continue;
}
final Constructor<? extends EdsdkErrorException> constructor;
try {
constructor = aClass.getConstructor(String.class);
} catch (NoSuchMethodException e) {
log.error("Missing constructor with string (message) for {}", value);
throw e;
}
final EdsdkErrorException exception = constructor.newInstance("AnyMessage");
Assertions.assertEquals("AnyMessage", exception.getMessage());
}
}
public FXBrowserWindowSE(String startURL) {
try {
initUI(startURL);
} catch (IllegalStateException ex) {
try {
EventQueue.invokeAndWait(new Runnable() {
@Override
public void run() {
new JFXPanel();
}
});
} catch (InterruptedException iex) {
Log.e(iex);
throw ex;
} catch (InvocationTargetException ite) {
Log.e(ite);
throw ex;
}
initUI(startURL);
}
}
/**
* Returns the elements of this enum class or null if this
* Class object does not represent an enum type;
* identical to getEnumConstants except that the result is
* uncloned, cached, and shared by all callers.
*/
T[] getEnumConstantsShared() {
if (enumConstants == null) {
if (!isEnum()) return null;
try {
final Method values = getMethod("values");
java.security.AccessController.doPrivileged(
new java.security.PrivilegedAction<Void>() {
public Void run() {
values.setAccessible(true);
return null;
}
});
@SuppressWarnings("unchecked")
T[] temporaryConstants = (T[])values.invoke(null);
enumConstants = temporaryConstants;
}
// These can happen when users concoct enum-like classes
// that don't comply with the enum spec.
catch (InvocationTargetException | NoSuchMethodException |
IllegalAccessException ex) { return null; }
}
return enumConstants;
}
protected Maybe<Object> invoke() {
findMethod();
if (method.isPresent()) {
Method m = method.get();
checkCallAllowed(m);
try {
// Value is most likely another BrooklynDslDeferredSupplier - let the caller handle it,
return Maybe.of(Reflections.invokeMethodFromArgs(instance, m, instanceArgs));
} catch (IllegalArgumentException | IllegalAccessException | InvocationTargetException e) {
// If the method is there but not executable for whatever reason fail with a fatal error, don't return an absent.
throw Exceptions.propagateAnnotated("Error invoking '"+toStringF(fnName, instanceArgs)+"' on '"+instance+"'", e);
}
} else {
// could do deferred execution if an argument is a deferred supplier:
// if we get a present from:
// new Invoker(obj, fnName, replaceSuppliersWithNull(args)).findMethod()
// then return a
// new DslDeferredFunctionCall(...)
return Maybe.absent(new IllegalArgumentException("No such function '"+fnName+"' taking args "+args+" (on "+obj+")"));
}
}
@TargetApi(26)
private boolean isChannelBlocked(@ChannelDefinitions.ChannelId String channelId) {
// Use non-compat notification manager as compat does not have getNotificationChannel (yet).
NotificationManager notificationManager =
ContextUtils.getApplicationContext().getSystemService(NotificationManager.class);
/*
The code in the try-block uses reflection in order to compile as it calls APIs newer than
our compileSdkVersion of Android. The equivalent code without reflection looks like this:
NotificationChannel channel = notificationManager.getNotificationChannel(channelId);
return (channel.getImportance() == NotificationManager.IMPORTANCE_NONE);
*/
// TODO(crbug.com/707804) Remove the following reflection once compileSdk is bumped to O.
try {
Method getNotificationChannel = notificationManager.getClass().getMethod(
"getNotificationChannel", String.class);
Object channel = getNotificationChannel.invoke(notificationManager, channelId);
Method getImportance = channel.getClass().getMethod("getImportance");
int importance = (int) getImportance.invoke(channel);
return (importance == NotificationManager.IMPORTANCE_NONE);
} catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
Log.e(TAG, "Error checking channel importance:", e);
}
return false;
}
public By getBy(String propertyName, String value) {
value = Objects.toString(value, "");
for (ObjectPropClass objectPropClass : OBJ_PROP_CLASSES) {
if (objectPropClass.propertyMethodMap.containsKey(propertyName)) {
Method method = objectPropClass.propertyMethodMap.get(propertyName);
try {
return (By) method.invoke(objectPropClass.classObject, value);
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
Logger.getLogger(ByObjectProp.class.getName()).log(Level.SEVERE, null, ex);
}
break;
}
}
Logger.getLogger(ByObjectProp.class.getName()).log(Level.SEVERE, "Find logic not implemented for - {0}", propertyName);
return null;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (ReflectionUtils.isEqualsMethod(method)) {
// Only consider equal when proxies are identical.
return (proxy == args[0]);
}
else if (ReflectionUtils.isHashCodeMethod(method)) {
// Use hashCode of reference proxy.
return System.identityHashCode(proxy);
}
else if (!initialized && ReflectionUtils.isToStringMethod(method)) {
return "Early singleton proxy for interfaces " +
ObjectUtils.nullSafeToString(getEarlySingletonInterfaces());
}
try {
return method.invoke(getSingletonInstance(), args);
}
catch (InvocationTargetException ex) {
throw ex.getTargetException();
}
}
public static InvocationHandler create( final Object delegate )
{
SecurityManager s = System.getSecurityManager();
if (s != null) {
s.checkPermission(new DynamicAccessPermission("access"));
}
return new InvocationHandler() {
public Object invoke( Object proxy, Method method, Object[] args )
throws Throwable
{
// This throws an IllegalArgument exception if the delegate
// is not assignable from method.getDeclaring class.
try {
return method.invoke( delegate, args ) ;
} catch (InvocationTargetException ite) {
// Propagate the underlying exception as the
// result of the invocation
throw ite.getCause() ;
}
}
} ;
}
@Override
public Object tryInvoke(String name, Object obj, Object... params) {
try {
Class<?> ctorClass = ctor.getDeclaringClass();
boolean invoke = true;
if (obj != null) {
if (obj instanceof Class<?>) {
invoke = ctorClass.equals(obj);
} else {
invoke = ctorClass.getName().equals(obj.toString());
}
}
invoke &= name == null || ctorClass.getName().equals(name);
if (invoke) {
return ctor.newInstance(params);
}
} catch (InstantiationException | IllegalArgumentException | IllegalAccessException xinstance) {
return Uberspect.TRY_FAILED;
} catch (InvocationTargetException xinvoke) {
throw JexlException.tryFailed(xinvoke); // throw
}
return Uberspect.TRY_FAILED;
}
private Object createInetSocketAddress(String host, int port)
throws NoSuchMethodException {
try {
Class<?> inetSocketAddressClass =
Class.forName("java.net.InetSocketAddress");
Constructor<?> inetSocketAddressCons =
inetSocketAddressClass.getConstructor(new Class<?>[]{
String.class, int.class});
return inetSocketAddressCons.newInstance(new Object[]{
host, new Integer(port)});
} catch (ClassNotFoundException |
InstantiationException |
InvocationTargetException |
IllegalAccessException e) {
throw new NoSuchMethodException();
}
}
private static boolean truncate(final FileSystem hadoopFs, final Path file, final long length) throws IOException {
if (truncateHandle != null) {
try {
return (Boolean) truncateHandle.invoke(hadoopFs, file, length);
}
catch (InvocationTargetException e) {
ExceptionUtils.rethrowIOException(e.getTargetException());
}
catch (Throwable t) {
throw new IOException(
"Truncation of file failed because of access/linking problems with Hadoop's truncate call. " +
"This is most likely a dependency conflict or class loading problem.");
}
}
else {
throw new IllegalStateException("Truncation handle has not been initialized");
}
return false;
}
public static InvocationHandler create( final Object delegate )
{
SecurityManager s = System.getSecurityManager();
if (s != null) {
s.checkPermission(new DynamicAccessPermission("access"));
}
return new InvocationHandler() {
public Object invoke( Object proxy, Method method, Object[] args )
throws Throwable
{
// This throws an IllegalArgument exception if the delegate
// is not assignable from method.getDeclaring class.
try {
return method.invoke( delegate, args ) ;
} catch (InvocationTargetException ite) {
// Propagate the underlying exception as the
// result of the invocation
throw ite.getCause() ;
}
}
} ;
}
/**
* Ensure that OssIndexPlugin properly assembles the proxy argument and passes it to the DependencyAuditor.
*/
@Test
public void httpSystemProxyTest() throws InvocationTargetException, IllegalAccessException, NoSuchMethodException {
Project project = mockProject();
// Mock the proxy being provided as project properties
mockSystemProxy(project, "http");
OssIndexPlugin plugin = new OssIndexPlugin();
AuditorFactory factory = mockAuditorFactory();
plugin.setAuditorFactory(factory);
// Simulate the process the gradle runs
runGradleSimulation(project, plugin);
verify(factory).getDependencyAuditor(null, Collections.EMPTY_SET, Collections.singletonList(getExpectedProxy("http")));
}
public static Object runRubyMethod(Object receiver, String methodName, Object... args) {
try {
Method m = ruby.getClass().getMethod("runRubyMethod", Class.class, Object.class, String.class, Object[].class);
return m.invoke(ruby, Object.class, receiver, methodName, args);
} catch (NoSuchMethodException nsme) {
throw new RuntimeException(nsme);
} catch (IllegalAccessException iae) {
throw new RuntimeException(iae);
} catch (java.lang.reflect.InvocationTargetException ite) {
printStackTrace(ite);
if (isDebugBuild) {
throw new RuntimeException(ite);
}
}
return null;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (method.getName().equals("getStatement")) {
return this.st;
} else {
try {
return method.invoke(this.delegate, args);
} catch (Throwable t) {
if (t instanceof InvocationTargetException
&& t.getCause() != null) {
throw t.getCause();
} else {
throw t;
}
}
}
}
/**
* Returns an estimate for the pth percentile of the stored values.
* <p>
* The implementation provided here follows the first estimation procedure presented
* <a href="http://www.itl.nist.gov/div898/handbook/prc/section2/prc252.htm">here.</a>
* </p><p>
* <strong>Preconditions</strong>:<ul>
* <li><code>0 < p < 100</code> (otherwise an
* <code>IllegalArgumentException</code> is thrown)</li>
* <li>at least one value must be stored (returns <code>Double.NaN
* </code> otherwise)</li>
* </ul></p>
*
* @param p the requested percentile (scaled from 0 - 100)
* @return An estimate for the pth percentile of the stored data
* @throws IllegalStateException if percentile implementation has been
* overridden and the supplied implementation does not support setQuantile
* values
*/
public double getPercentile(double p) {
if (percentileImpl instanceof Percentile) {
((Percentile) percentileImpl).setQuantile(p);
} else {
try {
percentileImpl.getClass().getMethod("setQuantile",
new Class[] {Double.TYPE}).invoke(percentileImpl,
new Object[] {new Double(p)});
} catch (NoSuchMethodException e1) { // Setter guard should prevent
throw new IllegalArgumentException(
"Percentile implementation does not support setQuantile");
} catch (IllegalAccessException e2) {
throw new IllegalArgumentException(
"IllegalAccessException setting quantile");
} catch (InvocationTargetException e3) {
throw new IllegalArgumentException(
"Error setting quantile" + e3.toString());
}
}
return apply(percentileImpl);
}
public static InvocationHandler create( final Object delegate )
{
SecurityManager s = System.getSecurityManager();
if (s != null) {
s.checkPermission(new DynamicAccessPermission("access"));
}
return new InvocationHandler() {
public Object invoke( Object proxy, Method method, Object[] args )
throws Throwable
{
// This throws an IllegalArgument exception if the delegate
// is not assignable from method.getDeclaring class.
try {
return method.invoke( delegate, args ) ;
} catch (InvocationTargetException ite) {
// Propagate the underlying exception as the
// result of the invocation
throw ite.getCause() ;
}
}
} ;
}
/**
* Waits until all events currently on the event queue have been processed.
* @throws IllegalThreadStateException if called on the AWT event dispatching thread
*/
public synchronized void waitForIdle() {
checkNotDispatchThread();
// post a dummy event to the queue so we know when
// all the events before it have been processed
try {
SunToolkit.flushPendingEvents();
EventQueue.invokeAndWait( new Runnable() {
public void run() {
// dummy implementation
}
} );
} catch(InterruptedException ite) {
System.err.println("Robot.waitForIdle, non-fatal exception caught:");
ite.printStackTrace();
} catch(InvocationTargetException ine) {
System.err.println("Robot.waitForIdle, non-fatal exception caught:");
ine.printStackTrace();
}
}
/**
* 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");
}
public static void aquireAndRun(Identifiable identifiable, ILockHandler handler){
Display display = Display.getDefault();
display.syncExec(new Runnable() {
@Override
public void run(){
ProgressMonitorDialog progress =
new ProgressMonitorDialog(display.getActiveShell());
try {
progress.run(true, true, new AcquireLockRunnable(identifiable, handler));
} catch (InvocationTargetException | InterruptedException e) {
logger.warn("Exception during acquire lock.", e);
}
}
});
}
private synchronized void initializeClusterManager(Configuration conf, ClusterType clusterType)
throws ClusterManagerInitilizationException
{
if (clusterManager != null) {
return;
}
String clusterManagerClassName = CacheConfig.getClusterManagerClass(conf, clusterType);
log.info("Initializing cluster manager : " + clusterManagerClassName);
try {
Class clusterManagerClass = conf.getClassByName(clusterManagerClassName);
Constructor constructor = clusterManagerClass.getConstructor();
ClusterManager manager = (ClusterManager) constructor.newInstance();
manager.initialize(conf);
setClusterManager(manager);
}
catch (ClassNotFoundException | NoSuchMethodException | InstantiationException |
IllegalAccessException | InvocationTargetException ex) {
String errorMessage = String.format("Not able to initialize ClusterManager class : {0} ",
clusterManagerClassName);
log.error(errorMessage, ex);
throw new ClusterManagerInitilizationException(errorMessage, ex);
}
}
/**
* Invokes NumericShaping shape(text,start,count) method.
*/
static void shape(Object shaper, char[] text, int start, int count) {
if (shapeMethod == null)
throw new AssertionError("Should not get here");
try {
shapeMethod.invoke(shaper, text, start, count);
} 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);
}
}
/**
* Inject the configuration opProps into the operator instance.
* @param operator
* @param properties
* @return Operator
*/
public static GenericOperator setOperatorProperties(GenericOperator operator, Map<String, String> properties)
{
try {
// populate custom opProps
BeanUtils.populate(operator, properties);
return operator;
} catch (IllegalAccessException | InvocationTargetException e) {
throw new IllegalArgumentException("Error setting operator properties", e);
}
}
public static void main(String args[]) throws InvocationTargetException, InterruptedException {
if (Util.getWMID() != Util.METACITY_WM) {
System.out.println("This test is only useful on Metacity");
return;
}
robot = Util.createRobot();
Util.waitForIdle(robot);
final FullscreenDialogModality frame = new FullscreenDialogModality();
frame.setUndecorated(true);
frame.setBackground(Color.green);
frame.setSize(500, 500);
frame.setVisible(true);
try {
robot.delay(100);
Util.waitForIdle(robot);
EventQueue.invokeAndWait(new Runnable() {
public void run() {
frame.enterFS();
}
});
robot.delay(200);
Util.waitForIdle(robot);
frame.checkDialogModality();
EventQueue.invokeAndWait(new Runnable() {
public void run() {
frame.exitFS();
}
});
} finally {
frame.dispose();
}
}
/** Returns a (deep) clone of this averagable. */
@Override
public Object clone() throws CloneNotSupportedException {
try {
Class<? extends Averagable> clazz = this.getClass();
Constructor<? extends Averagable> cloneConstructor = clazz.getConstructor(clazz);
return cloneConstructor.newInstance(this);
} catch (IllegalAccessException | InstantiationException | InvocationTargetException | NoSuchMethodException e) {
throw new CloneNotSupportedException("Cannot clone averagable: " + e.getMessage());
}
}
@Test
public void callThrowsInvocationTargetException() throws Exception {
Object context = new Object();
PropertyResolveRequest request = mock(PropertyResolveRequest.class);
given(request.getContext()).willReturn(context);
given(javaMethod.invoke(eq(context), argThat(arrayHasItem(argument)))).willThrow(InvocationTargetException.class);
Optional<Value> result = underTest.resolve(request);
assertEquals(Optional.<Value>absent(), result);
}
@Override
public void validateField(String name, Object o) {
try {
validateField(name, this.entryValidators, o);
} catch (NoSuchMethodException | IllegalAccessException
| InvocationTargetException | InstantiationException e) {
throw new RuntimeException(e);
}
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
@Override
public Object eInvoke ( final int operationID, final EList<?> arguments ) throws InvocationTargetException
{
switch ( operationID )
{
case ItemPackage.SCRIPT_CUSTOMIZATION_PIPELINE___GET_SCRIPT_ENGINE:
return getScriptEngine ();
case ItemPackage.SCRIPT_CUSTOMIZATION_PIPELINE___CUSTOMIZE__CUSTOMIZATIONREQUEST:
customize ( (CustomizationRequest)arguments.get ( 0 ) );
return null;
}
return super.eInvoke ( operationID, arguments );
}
@Test
public void importOfTypesInPackageInUnexistingPackage() throws NoSuchMethodException, IOException, InvocationTargetException, IllegalAccessException {
errorCollector = createMock(ErrorCollector.class);
errorCollector.recordSemanticError(Position.create(3, 0, 3, 24), "Import not resolved: foo.unexisting");
replay(errorCollector);
attemptToCompile("importOfTypesFromUnexistingPackage", Collections.emptyList());
verify(errorCollector);
}