0

I am creating an extensible java application using service providers concept. I have an abstract class named PoolTuningStrategy which is a service and USERS of my application provide their services in form of Service providers that extends this PoolTuningStrategy class and Users provide their implementations in form of jar files and my application uses ServiceLoader class to dynamically load the service providers as follows

int i=0;
for (PoolTuningStrategy foo : ServiceLoader.load(PoolTuningStrategy.class,urlloaders)) 
            strategy[i++]=foo;

Now strategy[] contains all set of implementations. Now my question is “How I can make a C++ class that extends my Java abstract class PoolTuningStrategy so that I can make use of C++ service providers.” Actually I want my application to be extended by Java and C++ programmers. I have done it using Java only but I don’t know how I can extend my Java application by having C++ implementations .

2 Answers2

3

You can make a Java class which delegates to a C++ implementation via JNI. However a C++ class cannot inherit from a Java one, nor can a Java class inherit from a C++. You have to use delegation instead.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • Good! Suppose i use JNI and delegation..Then can C++ users would be able to make use of my Service Provider Interface.How it works? Kindly send me links on this issue or give me code example – user3741146 Jul 08 '14 at 05:12
0

One way to get close to this is to use the commercial product JunC++ion, which effectively allows C++ classes to implement Java interfaces.

On the Java side, you could create a new concrete class CppPoolTuningStrategy that accepted an instance of a callback interface IPoolTuningStrategySPI. Your C++ users could then implement that interface.

This eliminates the need for your C++ users to write Java glue code. However, it does introduce the cost of a third-party product.

Andy Thomas
  • 84,978
  • 11
  • 107
  • 151
  • Can you please give a small code example on your second opinion of CppPoolTuningStrategy....I liked it because you stated that "This eliminates the need for your C++ users to write Java glue code"..I liked it and i want to make use of it but I need small example program because i could not understand idea of callback interface IPoolTuningStrategySPI... – user3741146 Jul 08 '14 at 05:04
  • Here's a little more detail. On the Java side, new concrete class `CppPoolTuningStrategy` is the proxy class for working with C++ implementations. Each instance works with the C++ implementation only through `com.mypackage.IPoolTuningStrategySPI`. On the C++ side, an implementation extends a C++ proxy class called `com::mypackage::IPoolTuningStrategy` created by JunC++ion -- e.g., `class MyTuningStrategy : public com::mypackage::IPoolTuningStrategy`. From the C++ side, you can then pass MyTuningStrategy to a Java method (through a JunC++ion-generated C++ proxy for the method). – Andy Thomas Jul 08 '14 at 13:20