mardi 6 janvier 2015

Java getDeclaredConstructor fails with NoSuchMethodException from JUnit

I have a base class, which uses reflection to create empty copy of concrete class using the following:



public IBase getEmptyCopy() {
Class type = this.getClass();
Constructor<?> ctor;
try {
ctor = type.getDeclaredConstructor();
ctor.setAccessible(true);
clonedObject =(Base) ctor.newInstance();
} catch (NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}


I've created a class called Test with the following main method:



public class Test {
public static void main(String [] args) {
....
ConcreteClass emptyInstance = (ConcreteClass) someInstance.getEmptyCopy();
}


All seem to work, however when I try to do the same in a JUnit test case:



@Test
public void test() {
....
ConcreteClass emptyInstance = (ConcreteClass) someInstance.getEmptyCopy();
}


I get an java.lang.NoSuchMethodException on the getDeclaredConstructor call.


can anyone explain what is the reason for that?


Thanks.






Aucun commentaire:

Enregistrer un commentaire