调用抽象的私有方法 Class
Invoking Private Methods of an Abstract Class
我有一个要求,我必须调用抽象的私有方法 class。
假设摘要 class 如下所示:-
public abstract class Base {
protected abstract String getName();
private String getHi(String v) {
return "Hi " + v;
}
}
有人可以告诉我有什么方法可以调用 getHi
(可能是通过 Reflection
或其他方式)以便我可以对其进行测试吗?我正在使用 Junit 4.12
和 Java 8
我已经完成了这个 question 但这里的方法在抽象中不是私有的 class。
我也经历过这个question即使这个没有抽象地谈论私有方法class。
我这里不是问我们是否应该测试私有方法或者测试私有方法的最佳策略是什么。网络上有很多与此相关的资源。我只是想问一下我们应该如何在 java.
中调用抽象 class 的私有方法
我可以如下调用抽象class的私有方法:-
假设我有一个 class 扩展抽象基础 class:-
public class Child extends Base {
protected String getName() {
return "Hello World";
}
}
然后我可以调用私有方法如下:-
Child child = new Child();
try {
Method method = Base.class.getDeclaredMethod("getHi", String.class);
method.setAccessible(true);
String output = (String) method.invoke(child, "Tuk");
System.out.println(output);
} catch (Exception e) {
e.printStackTrace();
}
我有一个要求,我必须调用抽象的私有方法 class。
假设摘要 class 如下所示:-
public abstract class Base {
protected abstract String getName();
private String getHi(String v) {
return "Hi " + v;
}
}
有人可以告诉我有什么方法可以调用 getHi
(可能是通过 Reflection
或其他方式)以便我可以对其进行测试吗?我正在使用 Junit 4.12
和 Java 8
我已经完成了这个 question 但这里的方法在抽象中不是私有的 class。
我也经历过这个question即使这个没有抽象地谈论私有方法class。
我这里不是问我们是否应该测试私有方法或者测试私有方法的最佳策略是什么。网络上有很多与此相关的资源。我只是想问一下我们应该如何在 java.
中调用抽象 class 的私有方法我可以如下调用抽象class的私有方法:-
假设我有一个 class 扩展抽象基础 class:-
public class Child extends Base {
protected String getName() {
return "Hello World";
}
}
然后我可以调用私有方法如下:-
Child child = new Child();
try {
Method method = Base.class.getDeclaredMethod("getHi", String.class);
method.setAccessible(true);
String output = (String) method.invoke(child, "Tuk");
System.out.println(output);
} catch (Exception e) {
e.printStackTrace();
}