jruby annotation method not getting called

2019-08-10 19:38发布

问题:

I have a jar named test.jar which contains following java classes:

Test.java

package test;
import java.lang.reflect.Method;
public class Test {

public static void yoyo(Object o) {

    Method[] methods = o.getClass().getMethods();

    for (Method method : methods) {
        CanRun annos = method.getAnnotation(CanRun.class);
        if (annos != null) {
            try {
                method.invoke(o);            
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
}

and interface CanRun.java

package test;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(value = ElementType.METHOD)
@Retention(value = RetentionPolicy.RUNTIME)
public @interface CanRun {
} 

and my ruby file is Main.rb

require 'java'
require 'test.jar'
java_import Java::test.Test

class Main
  def run
    Test.yoyo(Main.new)
  end

  java_annotation('CanRun')
  def onHi()
    puts "inside on Hi"
  end
end

app = Main.new
app.run

and I am running it by the following command: jruby Main.rb

but there is no output.

Basically,what I am trying to do is, calling yoyo() of Test.java from Main.rb and passing object of Main in yoyo().then yoyo() in Test.java will analyze all the functions of Main.rb having annotation CanRun and if found will call them, in our case onHi should be called. I checked that the object which I am passing in yoyo() is not null. The problem I am facing is that onHi is not getting called.

I tried a lot of things but nothing helped.

Am I using annotation properly in rb file or please suggest some other way.

回答1:

you annotation is not in the default package (nor is imported) thus instead :

java_annotation 'test.CanRun'

or

java_import "test.CanRun"
java_annotation :CanRun