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


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

Answers 1
Added at 2017-11-07 17:11

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() {

  public static void main(String[] args) {
    ... // Do something that I don't want
    ... // 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 =

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

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.

Answers to

How to access protected method of Java jar file&#39;s class

nr: #1 dodano: 2017-11-08 11:11

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

Source Show
◀ Wstecz