简体   繁体   English

是否可以在Android / dalvik中覆盖Java类中的本机方法?

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

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() ). 我使用EasyMock对TestMe类进行单元测试,其中一个方法(比如method(N n) )需要一个N类型的参数,它具有一个本机方法(比如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. method()需要在某个时刻调用N.nativeMethod() ,而我遇到的问题是我的N的Easymock模拟对象无法覆盖本机方法。 I do not own class N but I can refactor TestMe in any way necessary. 我没有N级,但我可以用任何必要的方式重构TestMe

I decided to make my own class FakeN extends N which overrides nativeMethod to do nothing: 我决定创建自己的类FakeN extends N ,它覆盖nativeMethod什么都不做:

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 FakeN s version. 但是当编译器没有抱怨时,当我运行测试时,看起来N.nativeMethod()是被调用的而不是FakeN的版本。

Is there a workaround here that I can use? 我可以使用这里的解决方法吗?

The native methods can be overridden just like any other methods, unless they are declared final . 除非将它们声明为final ,否则可以像其他任何方法一样覆盖本native方法。 Just be sure that you're calling TestMe.method(N n) with an instance of FakeN . 只要确保你打电话TestMe.method(N n)与实例FakeN

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM