我想替换 class 的函数我在哪里知道源代码。问题是我无法覆盖该函数,因为它是私有(private)的,而且我无法扩展类并覆盖整个功能,因为坏调用在每个可能的构造函数中。
现在我完全迷路了,我不知道如何实现所需的功能(主题化 Android VideoView 控件的控件,也称为 MediaController)。有没有办法用反射或类似的东西替换函数?或者甚至可以不调用父类(super class)的构造函数而是调用超父类(super class)?
这是一个非常基本的类,它显示了我的问题:
public class Base {
public Base(int state) {
// must be called
}
}
public class Example extends Base {
public Example(int state, boolean bla) {
super(state);
badCall();
}
public Example(int state) {
this(state, false);
}
private badCall() {
// doing bad things
}
}
另请注意,我需要有一个 Example
的实例,所以我不能简单地复制该类。
最佳答案
这是一个使用模拟框架 (jmockit) 的人为示例。输出是:
Original private method
Some other method
New private method
Some other method
public static void main(String[] args) {
A a = new A(); //prints Original private method
a.m2(); //prints Some other method
new MockUp<A>() {
@Mock
public void m() {
System.out.println("New private method");
}
};
A b = new A(); //prints New private method
b.m2(); //prints Some other method
}
static class A {
public A() {
m();
}
private void m() {
System.out.println("Original private method");
}
public void m2() {
System.out.println("Some other method");
}
}
关于java - 如何替换私有(private)函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14134983/