Add cast() method #305

Merged
jwharm merged 1 commit from cast-method into main 2025-11-27 23:29:43 +01:00
jwharm commented 2025-11-27 20:49:49 +01:00 (Migrated from github.com)

This allows to cast a type instance to another type, even if the Java type would not allow it.

This is of course terribly unsafe, but there is a runtime check using g_type_is_a() so at least there's a runtime type check.

The cast is intended to be used in some special cases:

  • When a Java wrapper class for a non-public GType doesn't fit the intended use case. In this case, a normal cast in Java to the intended type would raise a ClassCastException.
  • When a GObject is subclassed in Java, and the Java class overrides a virtual function, but it is still necessary to call the invoker method from Java. This isn't possible because Java-GI "merges" instance methods and virtual methods into one Java method, and when overridden, the virtual method will always take precedence over the parent's instance method. Using the cast() method introduced here, to "cast" the class to the parent type, it becomes possible again to call the instance method.
This allows to cast a type instance to another type, even if the Java type would not allow it. This is of course terribly unsafe, but there is a runtime check using `g_type_is_a()` so at least there's a runtime type check. The cast is intended to be used in some special cases: - When a Java wrapper class for a non-public GType doesn't fit the intended use case. In this case, a normal cast in Java to the intended type would raise a ClassCastException. - Example: #299 - When a GObject is subclassed in Java, and the Java class overrides a virtual function, but it is still necessary to call the invoker method from Java. This isn't possible because Java-GI "merges" instance methods and virtual methods into one Java method, and when overridden, the virtual method will always take precedence over the parent's instance method. Using the `cast()` method introduced here, to "cast" the class to the parent type, it becomes possible again to call the instance method. - Example: #303
Sign in to join this conversation.
No description provided.