java - 如何更改 swig 生成的代理类中的特定方法实现?

标签 java c++ abstract-class swig

我正在尝试使用 director 功能包装以下抽象类:

Listener.h:

class Listener {
  protected:
  void onEvent() = 0;
}

我的界面文件是这样的:

module(directors="1") Listener_Java
feature("director") Listener;
%{
#include "Listener.h"
%}
%include "Listener.h"

生成的 Java 代理类中的结果方法如下所示:

...
protected void onEvent() {
Listener_JavaJNI.Listener_onEvent();
}

我想做的是生成没有主体的抽象方法,如下所示:

protected void onEvent();

有什么简单的方法可以做到这一点吗?我想使方法抽象的原因是强制任何派生类重写此方法,因为如果它没有被重写,当在我的 C++ 代码中的其他地方调用此事件时,会出现异常(因为它试图调用纯未实现的虚函数)

最佳答案

来自SWIG documentation about Directors :

Why isn't the proxy class declared abstract? Why aren't the director upcall methods in the proxy class declared abstract?

Declaring the proxy class and its methods abstract would break the JNI argument marshalling and SWIG's downcall functionality (going from Java to C++.) Create an abstract Java subclass that inherits from the director-enabled class instead. Using the previous Foo class example:

public abstract class UserVisibleFoo extends Foo {
  /** Make sure user overrides this method, it's where the upcall
   * happens.
   */
  public abstract void method_upcall(Foo foo_object);

  /// Downcast from Foo to UserVisibleFoo
  public static UserVisibleFoo downcastUserVisibleFoo(Foo foo_object)
  {
    try {
     return (foo_object != null ? (FooDerived) Foo.downcastFoo(foo_object) : null);
    }

    catch (ClassCastException exc) {
      // Wasn't a FooDerived object, some other subclass of Foo
      return null;
    }
  }
}

This doesn't prevent the user from creating subclasses derived from Foo, however, UserVisibleFoo provides the safety net that reminds the user to override the method_upcall() method.

关于java - 如何更改 swig 生成的代理类中的特定方法实现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39265736/

相关文章:

c++ - 如何通过存储在 std::list 中的指针删除对象?

c# - 抽象不能代替部分吗?

java - 使用 Java Streams 从字符串数字列表中查找最大数字

Java 泛型和集合阅读引用

Java BigInteger testBit 64 位长

c++ - 多库 CMakeLists.txt

c++ - 如何使用 const 成员变量设置数组大小?

java - 无法在 Linux 中加载库 MediaInfo

c# - 序列化和恢复未知类

php - 接口(interface)和抽象类的优点是什么?