首页 > 解决方案 > 通过反射获取非静态方法中本地类的构造函数

问题描述

我需要JUnit4 测试方法中Constructor<TestClass>的本地类实例。TestClass

public void testMethod() throws NoSuchMethodException {
    class TestClass {
    }
    
    Constructor<TestClass> constructor = TestClass.class.getDeclaredConstructor();

    // dos sth in test
}

当我尝试使用获取构造函数时,getDeclaredConstructor()我得到了错误NoSuchMethodException()

我试图在我的 IDE 暂存器中运行相同的横向逻辑,并找到了构造函数。不同的是在STATIC方法TestClass中声明了。

我的问题是为什么会出现这个问题,它与静态/非静态方法有什么关系,以及如何在我的测试方法中解决这个问题。


更新:

我通过下载所有构造函数(获取单项数组)找到了解决方法。但是我仍然不明白为什么我不能直接在我的情况下获得无参数(或任何其他)构造函数。

public void testMethod() {
    class TestClass {
    }

    Constructor<TestClass>[] constructors = (Constructor<TestClass>[]) TestClass.class.getDeclaredConstructors();

    // constructors[0] <- get needed constructor
}

标签: javareflectionconstructorlocal-class

解决方案


推荐阅读