How to test a private constructor in Java application? [duplicate]

Using reflection, you can invoke a private constructor:

Constructor<Util> c = Utils.class.getDeclaredConstructor();
c.setAccessible(true);
Utils u = c.newInstance(); // Hello sailor

However, you can make even that not possible:

private Utils() {
    throw new UnsupportedOperationException();
}

By throwing an exception in the constructor, you prevent all attempts.

I would make the class itself final too, just “because”:

public final class Utils {
    private Utils() {
        throw new UnsupportedOperationException();
    }
}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)