How can I define a Java interface in JRuby rather than implement one?

563 Views Asked by At

I would like to invoke a Java API from JRuby that requires a Java interface, not a concrete class. The Java API uses java.lang.reflect.proxy to implement functionality based on the interface. I have found numerous examples of implementing a java interface with JRuby. However, I need to simply define a java interface in JRuby, not implement one. I can of course define an interface in Java and use this as the interface argument to the API via intf.java_class. However, for convenience, I'd like to be able to directly define the interface from JRuby code.

Update: Here's the Java API I want to invoke from JRuby:

public interface Query {
    <T> Collection<T> execute(Class<T> intf, String sql, Object... args);
}  

The Java API requires that the intf argument be an interface, not a class. This is due to the fact that the implementation uses java.lang.reflect.proxy to provide a collection of data objects that can be accessed via the provided interface. Java's java.lang.reflect.proxy will only work with interfaces. As an example, suppose I were reading rows from a database that represented log statements. If I were invoking this from java I might define my data via

public interface LogRecord {
    int id();
    Timestamp when();
    String msg();
    String level();
    String logger();
    String thread();
}

and pass LogRecord.class as the first argument to the Query.execute method.

1

There are 1 best solutions below

0
kristianp On

I don't think it can be done, because the Java class would have to inherit from the ruby interface, and apparently Java classes can't inherit from a JRuby class:

https://github.com/jruby/jruby/wiki/CallingJavaFromJRuby#java-classes-cant-inherit-from-a-jruby-class