jrubyjrubyonrails

How to access protected method of Java jar file's class


I am using a Java command-line application (which is open-source) as a jar file for my jrubyonrails project. The main application is like following

public class Decoder extends Annotator {
  public Decoder() {
    super();
  }

  public static void main(String[] args) {
    ... // Do something that I don't want
    myDesiredMethod();
    ... // And some other thing
  }
...
}

There are many steps which I want to skip, I only want myDesiredMethod function. And it is a protected method from the parent Annotator class.

public class Annotator extends Helper {
...
  protected SomeClass myDesiredMethod(boolean reMap) throws Exception { ... }
...
}

Annotator class does not have any public constructor so that I cannot:

ann = Annotator.new

It raises this error: TypeError: no public constructors for Annotator.

Then I try to implement another class which inherits Annotator in order to access myDesiredMethod. This is the jruby code I have tried so far

require 'java'
require 'decoder.jar'

java_import java.util.ArrayList
java_import java.lang.StringBuilder

module MyModule
  class RuDecoder < Annotator
    include_package 'com.decoder'
    def self.my_method
        myDesiredMethod
    end
end

It returns the error: NoMethodError: undefined method 'myDesiredMethod' for MyModule::RuDecoder:Class. Seems jruby does not look for the method of the parent class.

Is there any solution in my case, I don't want to rebuild the java library to jar and manually put it into my program every time it has an update.


Solution

  • Turns out that I made thing over-complicated. I can call the default constructor of Annotator as following:

      constructors = Annotator.java_class.declared_constructors.first
      constructors.accessible = true
      annotator = constructors.new_instance.to_java
    

    And use simple call myDesiredMethod: annotator.myDesiredMethod