M. Dudek
M. Dudek

Reputation: 1085

Get constructor for local-class in non-static method by reflection

I need Constructor<TestClass> instance for local class TestClass in my JUnit4 test method.

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

    // dos sth in test
}

When I'm trying get constructor using getDeclaredConstructor() I'm getting the error NoSuchMethodException().

I tried to run the same sideways logic in my IDE scratch and the constructor is found. The difference is that there TestClass is declared in the STATIC method.

My question is why this problem occurs and how does it relate to the static / non-static method, and how can I get around this problem in my test method.


UPDATE:

I found a workaround by downloading all the constructors (getting a one-item array). But I still do not understand why I cannot get an argumentless (or any other) constructor directly in my case.

public void testMethod() {
    class TestClass {
    }

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

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

Upvotes: 0

Views: 221

Answers (0)

Related Questions