mercredi 22 novembre 2017

Why is my private constructor public when checked with reflection?

I have (among many other Util classes which do not have this problem) a class FileUtil which fails the test for having a private constructor.

The class definition is:

public final class FileUtil {

    /**
     * Hidden constructor to prevent instantiation.
     */
    private FileUtil() {
    }
    // ...
    // many static methods
}

As mentioned above I have many other classes which are tested for having private constructors. The test method is:

@Test
public void testPrivateConstructor() throws Exception {
    Constructor<FileUtil> constructor = FileUtil.class.getDeclaredConstructor();
    Assert.assertTrue("Constructor is not private", Modifier.isPrivate(constructor.getModifiers()));
    constructor.setAccessible(true);
    constructor.newInstance();
}

But for this class - and only for this class - the isPrivate() method returns false and if checking in the debugger the constructor indeed is shown as public. However, if trying to call the constructor programmatically, Eclipse tells me the method is not visible.

I'm working with Eclipse and Maven and the problem shows in Eclipse and also on the command line when calling the Maven build. So it's really a Java problem, but as I use this pattern throughout my library without problems I do not see why it fails with this class only.

Any thoughts?





Aucun commentaire:

Enregistrer un commentaire