This does not solve the significant problem when empty private constructors do not need coverage, but in order to draw a JaCoCo report on an empty private constructor, you need to call it. How do you do this? You call it in a static initialization block.
public class MyClass { static { new MyClass(); } private MyClass(){} }
EDIT: It turned out that there is no guarantee that a static initialization block will execute. Thus, we restrict ourselves to using methods as follows:
static <T> void callPrivateConstructorIfPresent(Class<T> clazz){ try{ Constructor<T> noArgsConstructor = clazz.getDeclaredConstructor(); if(!noArgsConstructor.isAccessible()){ noArgsConstructor.setAccessible(true); try { noArgsConstructor.newInstance(); } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { e.printStackTrace(); } noArgsConstructor.setAccessible(false); } } catch(NoSuchMethodException e){} }
source share