mardi 17 janvier 2017

Java reflection - Call a static method of a generic class that has private constructor

I'm writing a java template to test the methods of my classes. The classes to be tested have a private constructor and static methods:

public class ProdClass {
  private ProdClass() {
  }

  public static EnumType myMethod() {
    // do something
  }
}

In my template class for testing i write this code using the java reflection:

String className = "com.myproject.mypackage.ProdClass";
String testMethodName = "myMethod";
Object[] obj = {};

... OTHER CODE FOR RENDERING ...

Class<?> params[] = new Class[obj.length];
for (int i = 0; i < obj.length; i++) {
    if (obj[i] instanceof Integer) {
        params[i] = Integer.TYPE;
    } else if (obj[i] instanceof String) {
        params[i] = String.class;
    } else if (obj[i] instanceof EnumType) {
        params[i] = EnumType.class;
    }
}

Class<?> cls = null;
Method testMethod = null;

try {
    cls = Class.forName(className);
    testMethod = cls.getDeclaredMethod(testMethodName, params);
} catch (NoSuchMethodException e1) {
     e1.printStackTrace();
 } catch (SecurityException e1) {
    e1.printStackTrace();
 } catch (ClassNotFoundException e1) {
     e1.printStackTrace();
}

Object resultTest = null;
try {
        resultTest = testMethod.invoke(cls.newInstance(),obj);
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | InstantiationException e) {
    e.printStackTrace();
}

if (resultTest != null) {
    System.out.println(" Result: " + resultTest.toString());
}

But I get the following error:

java.lang.IllegalAccessException: Class com.myproject.testpackage.TestTemplate$1$1 can not access a member of class com.myproject.mypackage.ProdClass with modifiers "private"
at sun.reflect.Reflection.ensureMemberAccess(Unknown Source)
at java.lang.Class.newInstance(Unknown Source)
at com.myproject.testpackage.TestTemplate$1$1.run(TestTemplate.java:264)
at java.lang.Thread.run(Unknown Source)

Because I have a private constructor. Would someone know how to solve the problem without becoming public the constructor.

Thanks a lot.





Aucun commentaire:

Enregistrer un commentaire