【问题标题】:NoSuchMethodException when using reflection to instantiate protected constructor使用反射实例化受保护的构造函数时出现 NoSuchMethodException
【发布时间】:2017-01-09 08:10:30
【问题描述】:

这是我第一次使用反射,不知道我在实例化受保护的构造函数时犯了什么错误。下面是我实例化JsonProcessingException 的构造函数的代码。

getDeclaredConstructor 导致 NoSuchMethodException,尽管此异常类具有带一、二和三参数的受保护构造函数。

final Constructor<JsonProcessingException> constructor = 
    JsonProcessingException.class
        .getDeclaredConstructor(Object.class, Object.class);
constructor.setAccessible(true);

我的假设:我读到我们可以使用反射来实例化私有构造函数,所以我假设 protected 也可以实例化。

【问题讨论】:

    标签: java reflection constructor protected


    【解决方案1】:

    您还必须考虑构造函数的参数类型,而不仅仅是数字。 JsonProcessingException 没有一个以两个Objects 作为参数的构造函数,但一个以String 和一个JsonLocation 以及一个以String 和一个Throwable 为参数的构造函数。要访问第二个构造函数,可以这样写:

    final Constructor<JsonProcessingException> constructor = 
        JsonProcessingException.class
            .getDeclaredConstructor(new Class[]{String.class, Throwable.class});
    constructor.setAccessible(true);
    JsonProcessingException ex = constructor.newInstance(msg, throwable);
    

    另见http://tutorials.jenkov.com/java-reflection/constructors.html

    【讨论】:

      【解决方案2】:

      您的方法几乎是正确的,但您试图反映不存在的构造函数。例如,您必须通过正确的签名

      JsonProcessingException.class
          .getDeclaredConstructor(String.class, Throwable.class)
      

      【讨论】:

      • 没有通过 Object.class 获取任何具有单个参数的构造函数的通用方法?
      • @Vishwanathgowdak 否(除非参数类型是真的和Object)。你必须知道参数类型。如果您需要不那么严格的匹配,那么您应该遍历getDeclaredConstructors() 以找到适合的构造函数
      猜你喜欢
      • 2014-04-22
      • 2013-10-06
      • 2018-03-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-26
      • 2011-09-12
      • 1970-01-01
      相关资源
      最近更新 更多