精华内容
下载资源
问答
  • 2021-08-12 10:48:02

    InvocationTargetException异常由Method.invoke(obj, args...)方法抛出。当被调用的方法的内部抛出了异常而没有被捕获时,将由此异常接收!!!
    例子:
            

    示例:

    1. package com.zzj.test.reflect;  
        
      public class Reflect {  
          public void run(int i) throws ZeroException {  
              B b = new B();  
              b.run(i);  
          }  
      }  
        
      class B {  
          public void run(int i) throws ZeroException {  
              if (i < 0) {  
                  throw new ZeroException("参数不能小于零!");  
              }  
              System.out.println("参数:" + i);  
        
          }  
      }  
        
      class ZeroException extends Exception {  
          private static final long serialVersionUID = 1L;  
        
          private String detailMessage;  
        
          public ZeroException(String detailMessage) {  
              this.detailMessage = detailMessage;  
          }  
        
          public String getMessage() {  
              return detailMessage;  
          }  
      }  

    测试:

    1. package com.zzj.test.reflect;  
        
      import java.lang.reflect.InvocationTargetException;  
      import java.lang.reflect.Method;  
        
      public class Test {  
          public static void main(String[] args) {  
              try {  
                  Class<?> clazz = Class.forName("com.zzj.test.reflect.Reflect");  
                  Method method = clazz.getMethod("run", int.class);  
                  method.invoke(clazz.newInstance(), -1);  
              } catch (ClassNotFoundException e) {  
                  e.printStackTrace();  
              } catch (SecurityException e) {  
                  e.printStackTrace();  
              } catch (NoSuchMethodException e) {  
                  e.printStackTrace();  
              } catch (IllegalArgumentException e) {  
                  e.printStackTrace();  
              } catch (IllegalAccessException e) {  
                  e.printStackTrace();  
              } catch (InvocationTargetException e) {  
                  System.out.println("此处接收被调用方法内部未被捕获的异常");  
                  e.printStackTrace();  
              } catch (InstantiationException e) {  
                  e.printStackTrace();  
              }  
          }  
      }  

    输出:

    1. 此处接收被调用方法内部未被捕获的异常  
    2. java.lang.reflect.InvocationTargetException  
    3.     at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)  
    4.     at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)  
    5.     at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)  
    6.     at java.lang.reflect.Method.invoke(Unknown Source)  
    7.     at com.zzj.test.reflect.Test.main(Test.java:11)  
    8. Caused by: com.zzj.test.reflect.ZeroException: 参数不能小于零!  
    9.     at com.zzj.test.reflect.B.run(Reflect.java:13)  
    10.     at com.zzj.test.reflect.Reflect.run(Reflect.java:6)  
    11.     ... 5 more  

    也可以直接打印目标异常:

    1. package com.zzj.test.reflect;  
        
      import java.lang.reflect.InvocationTargetException;  
      import java.lang.reflect.Method;  
        
      public class Test {  
          public static void main(String[] args) {  
              try {  
                  Class<?> clazz = Class.forName("com.zzj.test.reflect.Reflect");  
                  Method method = clazz.getMethod("run", int.class);  
                  method.invoke(clazz.newInstance(), -1);  
              } catch (ClassNotFoundException e) {  
                  e.printStackTrace();  
              } catch (SecurityException e) {  
                  e.printStackTrace();  
              } catch (NoSuchMethodException e) {  
                  e.printStackTrace();  
              } catch (IllegalArgumentException e) {  
                  e.printStackTrace();  
              } catch (IllegalAccessException e) {  
                  e.printStackTrace();  
              } catch (InvocationTargetException e) {  
                  System.out.println("此处接收被调用方法内部未被捕获的异常");  
                  Throwable t = e.getTargetException();// 获取目标异常  
                  t.printStackTrace();  
              } catch (InstantiationException e) {  
                  e.printStackTrace();  
              }  
          }  
      }  

    输出:

    1. 此处接收被调用方法内部未被捕获的异常  
    2. com.zzj.test.reflect.ZeroException: 参数不能小于零!  
    3.     at com.zzj.test.reflect.B.run(Reflect.java:13)  
    4.     at com.zzj.test.reflect.Reflect.run(Reflect.java:6)  
    5.     at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)  
    6.     at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)  
    7.     at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)  
    8.     at java.lang.reflect.Method.invoke(Unknown Source)  
    9.     at com.zzj.test.reflect.Test.main(Test.java:11)  
    更多相关内容
  • Jquery实现Ajax异步提交时报错”Uncaught TypeError: Illegal invocation”,如下图: 排查发现错误在于此: 代码如下: data:{“search_value”:$(‘input[name=search_value]’),”order_source”:buyerType,”...
  • F12看到后台报了个错误:Uncaught TypeError: Illegal invocation,百度了一下,找到了解决方法。 解决方法:在ajax请求的参数中添加如下两个参数: $.ajax({ ..., processData: false, contentType: false, .....
  • 主要介绍了Ajax方式上传文件报错"Uncaught TypeError: Illegal invocation",非常不错,具有一定的参考借鉴价值,需要的朋友可以参考下
  • NULL 博文链接:https://kdisk-sina-com.iteye.com/blog/258942
  • Remote Method Invocation是一种机制,能够让在某个 Java 虚拟机上的对象调用另一个 Java 虚拟机中的对象上的方法。 编写一个RMI的步骤 定义一个远程接口,此接口需要继承java.rmi.Remote 开发远程接口的实现类 创建...
  • invocation-chain-monitor RPC调用链监控
  • 一、Field类和InvocationTargetException类 InvocationTargetException 是一个经过检查的异常,它包装了被调用的方法或构造函数抛出的异常。Field提供有关类或接口的单个​​字段的信息和动态访问。反射字段可以是类...

    一、Field类和InvocationTargetException类

    InvocationTargetException 是一个经过检查的异常,它包装了被调用的方法或构造函数抛出的异常。Field提供有关类或接口的单个​​字段的信息和动态访问。反射字段可以是类(静态)字段或实例字段。下面我将从源码角度详细介绍Field类和InvocationTargetException类内部源码

    二、Field类源码介绍

    Field类继承了AccessibleObject类,同时实现了接口Member

    public final
    class Field extends AccessibleObject implements Member {
    }
    

    下面定义了一些基本变量

    	private Class<?>            clazz;
        private int                 slot;
        private String              name;
        private Class<?>            type;
        private int                 modifiers;
        private transient String    signature;
        private transient FieldRepository genericInfo;
        private byte[]              annotations;
        private FieldAccessor fieldAccessor;
        private FieldAccessor overrideFieldAccessor;
        private Field               root;
    

    获取泛型签名

    private String getGenericSignature() {return signature;}
    

    获取泛型工厂

    private GenericsFactory getFactory() {
            Class<?> c = getDeclaringClass();
            // create scope and factory
            return CoreReflectionFactory.make(c, ClassScope.make(c));
        }
    

    获取字段存储库

    private FieldRepository getGenericInfo() {
            // lazily initialize repository if necessary
            if (genericInfo == null) {
                // create and cache generic info repository
                genericInfo = FieldRepository.make(getGenericSignature(),
                                                   getFactory());
            }
            return genericInfo; //return cached repository
        }
    

    Field的构造方法

    Field(Class<?> declaringClass,
              String name,
              Class<?> type,
              int modifiers,
              int slot,
              String signature,
              byte[] annotations)
        {
            this.clazz = declaringClass;
            this.name = name;
            this.type = type;
            this.modifiers = modifiers;
            this.slot = slot;
            this.signature = signature;
            this.annotations = annotations;
        }
    

    包私有例程(通过 ReflectAccess 暴露给 java.lang.Class)返回该字段的副本。 副本的“根”字段指向此字段。

    Field copy() {
    
            if (this.root != null)
                throw new IllegalArgumentException("Can not copy a non-root Field");
    
            Field res = new Field(clazz, name, type, modifiers, slot, signature, annotations);
            res.root = this;
            res.fieldAccessor = fieldAccessor;
            res.overrideFieldAccessor = overrideFieldAccessor;
    
            return res;
        }
    

    返回表示类或接口的 Class 对象,该类或接口声明了由此 Field 对象表示的字段

    public Class<?> getDeclaringClass() {
            return clazz;
        }
    

    获取字段名称

    public String getName() {
            return name;
        }
    

    获取修饰符

    public int getModifiers() {
            return modifiers;
        }
    

    判断是否是枚举

    public boolean isEnumConstant() {
            return (getModifiers() & Modifier.ENUM) != 0;
        }
    

    判断是否是合成字段

    public boolean isSynthetic() {
            return Modifier.isSynthetic(getModifiers());
        }
    

    定义获取类型

    public Class<?> getType() {
            return type;
        }
    

    获取泛型类型

    public Type getGenericType() {
            if (getGenericSignature() != null)
                return getGenericInfo().getGenericType();
            else
                return getType();
        }
    

    将此Field与指定的对象进行比较

    public boolean equals(Object obj) {
            if (obj != null && obj instanceof Field) {
                Field other = (Field)obj;
                return (getDeclaringClass() == other.getDeclaringClass())
                    && (getName() == other.getName())
                    && (getType() == other.getType());
            }
            return false;
        }
    

    获取哈希值

     public int hashCode() {
            return getDeclaringClass().getName().hashCode() ^ getName().hashCode();
        }
    

    定义返回描述此Field的字符串

    public String toString() {
            int mod = getModifiers();
            return (((mod == 0) ? "" : (Modifier.toString(mod) + " "))
                + getType().getTypeName() + " "
                + getDeclaringClass().getTypeName() + "."
                + getName());
        }
    

    转化为泛型字符串

    public String toGenericString() {
            int mod = getModifiers();
            Type fieldType = getGenericType();
            return (((mod == 0) ? "" : (Modifier.toString(mod) + " "))
                + fieldType.getTypeName() + " "
                + getDeclaringClass().getTypeName() + "."
                + getName());
        }
    

    在指定的对象上返回由此 Field 表示的字段的值。

     public Object get(Object obj)
            throws IllegalArgumentException, IllegalAccessException
        {
            if (!override) {
                if (!Reflection.quickCheckMemberAccess(clazz, modifiers)) {
                    Class<?> caller = Reflection.getCallerClass();
                    checkAccess(caller, clazz, obj, modifiers);
                }
            }
            return getFieldAccessor(obj).get(obj);
        }
    

    获取静态或实例布尔字段的值。

    public boolean getBoolean(Object obj)
            throws IllegalArgumentException, IllegalAccessException
        {
            if (!override) {
                if (!Reflection.quickCheckMemberAccess(clazz, modifiers)) {
                    Class<?> caller = Reflection.getCallerClass();
                    checkAccess(caller, clazz, obj, modifiers);
                }
            }
            return getFieldAccessor(obj).getBoolean(obj);
        }
    

    获取静态或实例字节字段的不同类型的值。

    public byte getByte(Object obj)
            throws IllegalArgumentException, IllegalAccessException
        {
            if (!override) {
                if (!Reflection.quickCheckMemberAccess(clazz, modifiers)) {
                    Class<?> caller = Reflection.getCallerClass();
                    checkAccess(caller, clazz, obj, modifiers);
                }
            }
            return getFieldAccessor(obj).getByte(obj);
        }
    public char getChar(Object obj)
            throws IllegalArgumentException, IllegalAccessException
        {
            if (!override) {
                if (!Reflection.quickCheckMemberAccess(clazz, modifiers)) {
                    Class<?> caller = Reflection.getCallerClass();
                    checkAccess(caller, clazz, obj, modifiers);
                }
            }
            return getFieldAccessor(obj).getChar(obj);
        }
    public short getShort(Object obj)
            throws IllegalArgumentException, IllegalAccessException
        {
            if (!override) {
                if (!Reflection.quickCheckMemberAccess(clazz, modifiers)) {
                    Class<?> caller = Reflection.getCallerClass();
                    checkAccess(caller, clazz, obj, modifiers);
                }
            }
            return getFieldAccessor(obj).getShort(obj);
        }
     public int getInt(Object obj)
            throws IllegalArgumentException, IllegalAccessException
        {
            if (!override) {
                if (!Reflection.quickCheckMemberAccess(clazz, modifiers)) {
                    Class<?> caller = Reflection.getCallerClass();
                    checkAccess(caller, clazz, obj, modifiers);
                }
            }
            return getFieldAccessor(obj).getInt(obj);
        }
    public long getLong(Object obj)
            throws IllegalArgumentException, IllegalAccessException
        {
            if (!override) {
                if (!Reflection.quickCheckMemberAccess(clazz, modifiers)) {
                    Class<?> caller = Reflection.getCallerClass();
                    checkAccess(caller, clazz, obj, modifiers);
                }
            }
            return getFieldAccessor(obj).getLong(obj);
        }
    public float getFloat(Object obj)
            throws IllegalArgumentException, IllegalAccessException
        {
            if (!override) {
                if (!Reflection.quickCheckMemberAccess(clazz, modifiers)) {
                    Class<?> caller = Reflection.getCallerClass();
                    checkAccess(caller, clazz, obj, modifiers);
                }
            }
            return getFieldAccessor(obj).getFloat(obj);
        }
    public double getDouble(Object obj)
            throws IllegalArgumentException, IllegalAccessException
        {
            if (!override) {
                if (!Reflection.quickCheckMemberAccess(clazz, modifiers)) {
                    Class<?> caller = Reflection.getCallerClass();
                    checkAccess(caller, clazz, obj, modifiers);
                }
            }
            return getFieldAccessor(obj).getDouble(obj);
        }
        
    

    设置某个对象的值。

     public void set(Object obj, Object value)
            throws IllegalArgumentException, IllegalAccessException
        {
            if (!override) {
                if (!Reflection.quickCheckMemberAccess(clazz, modifiers)) {
                    Class<?> caller = Reflection.getCallerClass();
                    checkAccess(caller, clazz, obj, modifiers);
                }
            }
            getFieldAccessor(obj).set(obj, value);
        }
    

    设置某个对象的布尔类型

    public void setBoolean(Object obj, boolean z)
            throws IllegalArgumentException, IllegalAccessException
        {
            if (!override) {
                if (!Reflection.quickCheckMemberAccess(clazz, modifiers)) {
                    Class<?> caller = Reflection.getCallerClass();
                    checkAccess(caller, clazz, obj, modifiers);
                }
            }
            getFieldAccessor(obj).setBoolean(obj, z);
        }
    

    设置某个对象的byte类型字

    public void setByte(Object obj, byte b)
            throws IllegalArgumentException, IllegalAccessException
        {
            if (!override) {
                if (!Reflection.quickCheckMemberAccess(clazz, modifiers)) {
                    Class<?> caller = Reflection.getCallerClass();
                    checkAccess(caller, clazz, obj, modifiers);
                }
            }
            getFieldAccessor(obj).setByte(obj, b);
        }
    

    设置某个对象的char类型字

     public void setChar(Object obj, char c)
            throws IllegalArgumentException, IllegalAccessException
        {
            if (!override) {
                if (!Reflection.quickCheckMemberAccess(clazz, modifiers)) {
                    Class<?> caller = Reflection.getCallerClass();
                    checkAccess(caller, clazz, obj, modifiers);
                }
            }
            getFieldAccessor(obj).setChar(obj, c);
        }
    

    设置某个对象的short类型字

     public void setShort(Object obj, short s)
            throws IllegalArgumentException, IllegalAccessException
        {
            if (!override) {
                if (!Reflection.quickCheckMemberAccess(clazz, modifiers)) {
                    Class<?> caller = Reflection.getCallerClass();
                    checkAccess(caller, clazz, obj, modifiers);
                }
            }
            getFieldAccessor(obj).setShort(obj, s);
        }
    

    设置某个对象的int类型字

     public void setInt(Object obj, int i)
            throws IllegalArgumentException, IllegalAccessException
        {
            if (!override) {
                if (!Reflection.quickCheckMemberAccess(clazz, modifiers)) {
                    Class<?> caller = Reflection.getCallerClass();
                    checkAccess(caller, clazz, obj, modifiers);
                }
            }
            getFieldAccessor(obj).setInt(obj, i);
        }
    

    设置某个对象的long类型字

     public void setLong(Object obj, long l)
            throws IllegalArgumentException, IllegalAccessException
        {
            if (!override) {
                if (!Reflection.quickCheckMemberAccess(clazz, modifiers)) {
                    Class<?> caller = Reflection.getCallerClass();
                    checkAccess(caller, clazz, obj, modifiers);
                }
            }
            getFieldAccessor(obj).setLong(obj, l);
        }
    

    设置某个对象的float类型字

    public void setFloat(Object obj, float f)
            throws IllegalArgumentException, IllegalAccessException
        {
            if (!override) {
                if (!Reflection.quickCheckMemberAccess(clazz, modifiers)) {
                    Class<?> caller = Reflection.getCallerClass();
                    checkAccess(caller, clazz, obj, modifiers);
                }
            }
            getFieldAccessor(obj).setFloat(obj, f);
        }
    

    设置某个对象的double类型字

    public void setDouble(Object obj, double d)
            throws IllegalArgumentException, IllegalAccessException
        {
            if (!override) {
                if (!Reflection.quickCheckMemberAccess(clazz, modifiers)) {
                    Class<?> caller = Reflection.getCallerClass();
                    checkAccess(caller, clazz, obj, modifiers);
                }
            }
            getFieldAccessor(obj).setDouble(obj, d);
        }
    

    获取字段地址,中间为具体实现类,最后是对外接口类

    private FieldAccessor getFieldAccessor(Object obj)
            throws IllegalAccessException
        {
            boolean ov = override;
            FieldAccessor a = (ov) ? overrideFieldAccessor : fieldAccessor;
            return (a != null) ? a : acquireFieldAccessor(ov);
        }
    private FieldAccessor acquireFieldAccessor(boolean overrideFinalCheck) {
            // First check to see if one has been created yet, and take it
            // if so
            FieldAccessor tmp = null;
            if (root != null) tmp = root.getFieldAccessor(overrideFinalCheck);
            if (tmp != null) {
                if (overrideFinalCheck)
                    overrideFieldAccessor = tmp;
                else
                    fieldAccessor = tmp;
            } else {
                // Otherwise fabricate one and propagate it up to the root
                tmp = reflectionFactory.newFieldAccessor(this, overrideFinalCheck);
                setFieldAccessor(tmp, overrideFinalCheck);
            }
    
            return tmp;
        }
    private FieldAccessor getFieldAccessor(boolean overrideFinalCheck) {
            return (overrideFinalCheck)? overrideFieldAccessor : fieldAccessor;
        }
    

    设置字段地址

    private void setFieldAccessor(FieldAccessor accessor, boolean overrideFinalCheck) {
            if (overrideFinalCheck)
                overrideFieldAccessor = accessor;
            else
                fieldAccessor = accessor;
            // Propagate up
            if (root != null) {
                root.setFieldAccessor(accessor, overrideFinalCheck);
            }
        }
    

    定于注解类型

    public <T extends Annotation> T getAnnotation(Class<T> annotationClass) {
            Objects.requireNonNull(annotationClass);
            return annotationClass.cast(declaredAnnotations().get(annotationClass));
        }
    

    定义获取注解类型

    public <T extends Annotation> T[] getAnnotationsByType(Class<T> annotationClass) {
            Objects.requireNonNull(annotationClass);
    
            return AnnotationSupport.getDirectlyAndIndirectlyPresent(declaredAnnotations(), annotationClass);
        }
    

    返回直接出现在此元素上的注释## 三、InvocationTargetException类源码介绍
    InvocationTargetException类

      public Annotation[] getDeclaredAnnotations()  {
            return AnnotationParser.toArray(declaredAnnotations());
        }
    

    定义注解泛型和注解键值对

    private transient Map<Class<? extends Annotation>, Annotation> declaredAnnotations;
    

    生成泛型-注解键值对

    private synchronized  Map<Class<? extends Annotation>, Annotation> declaredAnnotations() {
            if (declaredAnnotations == null) {
                Field root = this.root;
                if (root != null) {
                    declaredAnnotations = root.declaredAnnotations();
                } else {
                    declaredAnnotations = AnnotationParser.parseAnnotations(
                            annotations,
                            sun.misc.SharedSecrets.getJavaLangAccess().getConstantPool(getDeclaringClass()),
                            getDeclaringClass());
                }
            }
            return declaredAnnotations;
        }
    

    调用JVM获取注解byte数组

    private native byte[] getTypeAnnotationBytes0();
    

    定义获取注解类型对外接口类

    public AnnotatedType getAnnotatedType() {
            return TypeAnnotationParser.buildAnnotatedType(getTypeAnnotationBytes0(),
                                                           sun.misc.SharedSecrets.getJavaLangAccess().
                                                               getConstantPool(getDeclaringClass()),
                                                           this,
                                                           getDeclaringClass(),
                                                           getGenericType(),
                                                           TypeAnnotation.TypeAnnotationTarget.FIELD);
    }
    

    三、InvocationTargetException类

    InvocationTargetException类继承了ReflectiveOperationException类

    public class InvocationTargetException extends ReflectiveOperationException {
    }
    

    下面定义了通用串行ID

    private static final long serialVersionUID = 4085088731926701167L;
    

    返回目标

    private Throwable target;
    

    构造一个以 null 作为目标异常的 InvocationTargetException。

    protected InvocationTargetException() {
            super((Throwable)null);
    

    构造一个带有目标异常的 InvocationTargetException。

    public InvocationTargetException(Throwable target) {
            super((Throwable)null);  // Disallow initCause
            this.target = target;
        }
    

    构造一个带有目标异常和详细消息的 InvocationTargetException

    public InvocationTargetException(Throwable target, String s) {
            super(s, null);  // Disallow initCause
            this.target = target;
        }
    

    获取抛出的目标异常

    public Throwable getTargetException() {
            return target;
        }
    

    返回此异常的原因(抛出的目标异常,可能为null

    public Throwable getCause() {
            return target;
        }
    
    展开全文
  • 特殊的异常InvocationTargetException

    千次阅读 2020-12-18 10:54:43
    InvocationTargetException是什么 JavaDoc一上来就说了: InvocationTargetException is a checked exception that wraps an exception thrown by an invoked method or constructor. InvocationTargetException是...

    InvocationTargetException是什么

    JavaDoc一上来就说了:

    InvocationTargetException is a checked exception that wraps an exception thrown by an invoked method or constructor.
    InvocationTargetException是一个受检查异常,当被调用的方法或构造器内部抛出异常,该异常将会被包装成InvocationTargetException来进行接收

    以下是知乎作者RednaxelaFX对其的描述

    链接:https://www.zhihu.com/question/56718746/answer/150173531
    InvocationTargetException 存在的意义是什么?
    因为“原来的异常”无法直接以一种统一而又明确的方式表达出来,所以使用InvocationTargetException来将原来的异常包装起来,通过多加一层间接层的方式来提供统一的访问途径。
    Java方法可以静态声明它可能会抛出一组固定的异常类型。而反射API里,Method.invoke() 与 Constructor.newInstance() 这些方法有“双重身份”——它们既代表要调用指定的目标方法,自身也是一个方法;目标方法可能会抛出异常,而它们自身在调用目标方法前也可能会抛出一些异常(例如IllegalArgumentException)。它们要调用的目标方法可能抛出任意Throwable类的派生类的异常,但它们自身却不能根据要调用的目标而“动态”改变自己声明要抛出的异常类型,而只能静态声明一组可能抛出的异常类型。声明抛出Throwable或Exception的话,这就太宽泛,难以准确反映异常的原因和意图;但不声明成这么宽泛的异常类型的话又无法完整覆盖所有可能由目标方法抛出的异常。那怎么办?简单,新增一个check exception类型,InvocationTargetException,将原本由目标方法抛出的异常包装起来,这样就可以给Method.invoke() / Constructor.newInstance() 的调用者一个统一的接口,既明确了“这个异常是由目标方法抛出的,不是由我自己抛出的”的意图,又能完整覆盖目标方法所能抛出的所有异常类型(InvocationTargetException.getTargetException() / getCause() 的类型是Throwable)。

    大白话:在反射API里,Method.invoke() 与 Constructor.newInstance() 这些方法本身执行时会出现异常,同时被执行的方法或构造器内部也会出现异常,所以InvocationTargetException将被执行的方法或构造器内部抛出的异常进行包装,可通过InvocationTargetException.getTargetException() / getCause()进行获取,但不能直接使用InvocationTargetException,此时如果直接获取InvocationTargetException.getMessage()将会出现Null

    直接获取被执行的方法或构造器内部抛出的异常的两种方式

    • JDK反射,将会将异常信息封装到InvocationTargetException,可通过InvocationTargetException.getTargetException() / getCause()进行获取
    • ASM反射,可直接通过Exception获取

    Demo验证

    • 引入ASM相关依赖
    <dependency>
        <groupId>com.esotericsoftware</groupId>
    	<artifactId>reflectasm</artifactId>
    	<!-- 版本自行修改 -->
    	<version>1.11.7</version>
    </dependency>
    

    该依赖包底层使用的是如下依赖

    <dependency>
    	<groupId>org.ow2.asm</groupId>
    	<artifactId>asm</artifactId>
    	<version>5.1</version>
    </dependency>
    
    • 测试用例如下:
    import com.esotericsoftware.reflectasm.MethodAccess;
    
    import java.lang.reflect.InvocationTargetException;
    import java.lang.reflect.Method;
    import java.util.Objects;
    
    public class AA {
        public static void main(String[] args) {
    
            Demo demo = new Demo();
            try {
                Method method = findMethod(Demo.class, "haha", new Object[]{"niuwa"});
                method.setAccessible(true);
                method.invoke(demo, 0);
            } catch (InvocationTargetException e) {
                // 如果直接使用InvocationTargetException来接收,则可以使用e.getTargetException() 来进行获取
                System.out.println("---------- JDK Invoke Exception ----------");
                // JDK 反射调用,将调用方法抛出的异常放置在Cause中了,Exception为空
                System.out.println("Cause message by JDK reflection:" + e.getTargetException().getMessage());
                System.out.println("Exception message by JDK reflection:" + e.getMessage());
            } catch (Exception e) {
                // 如果直接使用Exception来接收,则可以使用e.getCause() 来进行获取
                System.out.println("---------- JDK Invoke Exception ----------");
                // JDK 反射调用,将调用方法抛出的异常放置在Cause中了,Exception为空
                System.out.println("Cause message by JDK reflection:" + e.getCause().getMessage());
                System.out.println("Exception message by JDK reflection:" + e.getMessage());
            }
    
            try {
                MethodAccess access = MethodAccess.get(Demo.class);
                int setNameIndex = access.getIndex("haha");
                access.invoke(demo, setNameIndex, 0);
            } catch (Exception e) {
                System.out.println("---------- ASM Invoke Exception ----------");
                // JDK 反射调用,将调用方法抛出的异常直接放置在Exception中了,Cause为空
                System.out.println("Cause message by ASM reflection:" + e.getCause());
                System.out.println("Exception message by ASM reflection:" + e.getMessage());
            }
        }
    
        private static Method findMethod(Class<? extends Object> clazz, String methodName, Object[] args) {
            Method[] var6;
            int var5 = (var6 = clazz.getDeclaredMethods()).length;
    
            for (int var4 = 0; var4 < var5; ++var4) {
                Method method = var6[var4];
                if (method.getName().equals(methodName) && Objects.equals(method.getParameterTypes().length, args.length)) {
                    return method;
                }
            }
    
            Class<?> superClass = clazz.getSuperclass();
            if (superClass != null) {
                return findMethod(superClass, methodName, args);
            } else {
                return null;
            }
        }
    }
    
    class Demo {
        public Demo() {
    
        }
    
        public void haha(int param) {
            System.err.println("计算结果:" + 10 / param);
        }
    }
    
    展开全文
  • Illegal invocation的报错

    这是因为使用jQuery发送ajax请求时,当请求体的数据为FormData的格式时,必须设置processData 和 contentType 属性

    使用原生js发送文件使用FormData数据格式时,不可以设置请求头。原因是FormData的数据格式为multipart/form-data

    展开全文
  • 默认情况下 Expectations 录制的函数,必须被执行一次,否则会报错 Missing 1 invocation to: 之类的错误。
  • 在andriod studio中push项目到gitee中报错:Invocation failed Unexpected end of file from server java.lang.RuntimeException: Invocation failed Unexpected end of file from server 解决方案:settings==》...
  • Invocation failed Unexpected end of file from server java.lang.RuntimeException: Invocation failed Unexpected end of file from server at org.jetbrains.git4idea....
  • Invocation failed Server returned invalidResponse. java.lang.RuntimeException:Invocation failed Server returned invalidResponse.at org.jetbrains.git4idea.http.GitAskPassXmlRpcClient.askUsername...
  • nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dumpService': Invocation of init method failed; nested exception is java.lang....
  • java.lang.reflect.InvocationTargetException

    千次阅读 2021-03-13 23:54:44
    java.lang.reflect.InvocationTargetException错误java.lang.reflect.InvocationTargetException'>java.lang.reflect.InvocationTargetException异常在JBOSS内执行程序,总是报这个异常。但是我用bat文件直接运行...
  • Spring AOP MethodInvocation拦截器调用原理

    千次阅读 多人点赞 2020-04-03 21:31:35
    前言 通过对JdkDynamicAopProxy的invoke方法的探究,发现invoke的核心是: 由匹配当前方法的advisor,例如与当前方法所匹配的所有before、...MethodInvocation invocation = new ReflectiveMethodInvocation(pro...
  • invocationHandler和invocation的区别 1.invocationhandler是执行具体invoke的地方 2.invocation可以保存 代理对象和方法和args,这样在invoke方法如果不在此处执行 例如interceptor中是最后传这个invocation给...
  • InvocationTargetException: 反射调用抛出,target为真实异常 UndeclaredThrowableException:jdk代理抛出,只有出现非接口定义的checkedException(非runtime非Error)才会抛出,undeclaredThrowable为真实异常
  • Retrofit最佳动态配置请求timeout办法–Invocation 最近重构项目需要调整, 需要区分普通上传和辅助功能校验的超时. 为了提高用户体验,需要动态去进行配置. 传统方式 1.OkHttpClient设置 最传统的设置 请求超时时间...
  • AIDL错误:Binder invocation to an incorrect interface
  • java.lang.reflect.InvocationTargetException at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke...
  • Invocation failed Unexpected end of file from server java.lang.RuntimeException: Invocation failed Unexpected end of file from server at org.jetbrains.git4idea.GitAppUtil.sendXmlRequest(GitApp...
  • 部分代码来自mybatis分页和spring-boot整合项目,项目地址是:http://git.oschina.net/free/Mybatis_PageHelper mybatis提供了拦截器Interceptor接口 ... Object intercept(Invocation invocation) throws T...
  • 可能数据库该字段预留长度太小,传来的数据该字段无法转化到数据库字段
  • nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userMongoRepository': Invocation of init method failed; nested exception is org.spring...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 176,072
精华内容 70,428
关键字:

invocation