我正在编写一个java模板来测试我的类的方法。 要测试的类具有私有构造函数和静态方法:
public class ProdClass {
private ProdClass() {
}
public static EnumType myMethod() {
// do something
}
}
在我的测试模板类中,我使用java反射编写此代码:
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());
}
但是我收到以下错误:
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)
因为我有一个私人构造函数。 有人会知道如何在不成为公共构造函数的情况下解决问题。
非常感谢。
答案 0 :(得分:1)
尝试替换
resultTest = testMethod.invoke(cls.newInstance(),obj);
与
Constructor constructor = constructor.getConstructor();
constructor.setAccessible(true);
resultTest = testMethod.invoke(constructor.newInstance(),obj);
答案 1 :(得分:0)
尝试:
Constructor constructor = cls.getConstructor();
constructor.setAccessible(true);
constructor.newInstance();