Is it possible to override a native method in a Java class in Android/dalvik?

限于喜欢 提交于 2019-12-05 19:05:27

问题


I am unit testing a class TestMe using EasyMock, and one of its methods (say method(N n)) expects a parameter of type N which has a native method (say nativeMethod()).

class TestMe {
    void method(N n) {
        // Do stuff

        n.nativeMethod();

        // Do more stuff
    }
}

method() needs to invoke N.nativeMethod() at some point, and the problem I'm having is that my Easymock mock object for N is unable to override the native method. I do not own class N but I can refactor TestMe in any way necessary.

I decided to make my own class FakeN extends N which overrides nativeMethod to do nothing:

class FakeN extends N {
    FakeN(int pointer) {
        super(pointer);
    }

    @Override
    public void nativeMethod(Object o) {
        // super.nativeMethod() is an actual native method defined as:
        // public native void nativeMethod(Object o)
        //
        // IGNORE
    }
}

but while the compiler does not complain, when I run the test it appears that N.nativeMethod() is the one being invoked and not FakeNs version.

Is there a workaround here that I can use?


回答1:


The native methods can be overridden just like any other methods, unless they are declared final. Just be sure that you're calling TestMe.method(N n) with an instance of FakeN.



来源:https://stackoverflow.com/questions/10940502/is-it-possible-to-override-a-native-method-in-a-java-class-in-android-dalvik

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!