0

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
}
3
  • 1
    Because this becomes an implicit constructor argument that is visible in Reflection. Commented Aug 18, 2021 at 10:59
  • Could you elaborate on your answer? Commented Aug 18, 2021 at 11:20
  • 1
    You found the constructor (via TestClass.class.getDeclaredConstructors()[0]). Now check its parameter types… Commented Aug 18, 2021 at 14:22

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.