lundi 23 mai 2016

Instantiating an Object using Java Reflection

I am testing a private method using JUnit and I am invoking it using Reflection. The error I am getting is java.lang.InstantiationException. I know it is not creating an instance of Class but I am not sure what I am doing wrong. Object object = clazz.newInstance(); is the line that throws Exception.

Method under test

 private int _getType(String type) {
    if ("DATE".equalsIgnoreCase(type)) return Types.DATE;
    if ("STRING".equalsIgnoreCase(type)) return Types.VARCHAR;
    if ("INT".equalsIgnoreCase(type)) return Types.INTEGER;
    if ("TIMESTAMP".equalsIgnoreCase(type)) return Types.TIMESTAMP;

    return Types.NULL;

}

JUnit test

@Test
public void testGetType() throws Exception {
    String type1 = "DATE";
    String type2 = "STRING";
    String type3 = "INT";
    String type4 = "TIMESTAMP";

    Class clazz = SpringStoredProcImpl.class;
    Object object = clazz.newInstance();

    Method method = object.getClass().getDeclaredMethod("getType", String.class);
    method.setAccessible(true);

    method.invoke(object, type1);

I don't have my asserts yet so please ignore it.

Thanks in advance.





Aucun commentaire:

Enregistrer un commentaire