Customer questions answered: Cross-platform method overrides in JNBridgePro
Here’s another interesting question from the support inbox.
Let’s say that you have a .NET class that contains a virtual method, and you want to override it in your Java code. The immediate answer would seem to be to proxy the .NET class, then write a Java class that extends the proxy class and override the method in the Java subclass. The problem is that while this will certainly override the method when the Java class is accessed from Java code, if the Java object is passed back to the .NET side – for example, as an argument in a method call – the new Java method won’t be seen; any calls to the virtual method will be handled by the original .NET class’s method.
Overrides are not yet directly supported by JNBridgePro, but there is a way to work around this issue and allow the underlying .NET code to see the Java-based override method, through the use of callbacks. Note that while this example assumes a Java-to-.NET project, the equivalent thing can be done in .NET-to-Java projects.
Let’s say that you have a C# class:
{
{
}
}
You will need to write some additional C# code:
public delegate int OverrideMethod(int i);
public class C2 : C
{
public OverrideMethod overrideMethod = null;
public override int myVirtualMethod(int i)
{
{
}
else
{
}
}
}
The class C2 must be a concrete class — that is, it cannot be abstract. This is important: you must be able to instantiate it, or you will see a different problem.
If you don’t have access to the C# source code so that you can modify the original dll, place C2 in a new dll that you create, and which you include in your application.
Then, proxy C, C2, and OverrideMethod, and make your new Java class extend C2. As part of the new Java class’s constructor, create and register a callback for overrideMethod:
{
{
}
}
public class J extends C2
{
{
}
}
Now, the overrides should work as expected.
Do you have a question about how to do something using JNBridgePro? Contact us at info@jnbridge.com.