简体   繁体   English

如何在JRuby中定义Java接口,而不是实现接口?

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

I would like to invoke a Java API from JRuby that requires a Java interface, not a concrete class. 我想从需要Java接口而不是具体类的JRuby调用Java API。 The Java API uses java.lang.reflect.proxy to implement functionality based on the interface. Java API使用java.lang.reflect.proxy来实现基于接口的功能。 I have found numerous examples of implementing a java interface with JRuby. 我发现了许多使用JRuby实现Java接口的示例。 However, I need to simply define a java interface in JRuby, not implement one. 但是,我只需要在JRuby中定义一个Java接口,而不要实现一个。 I can of course define an interface in Java and use this as the interface argument to the API via intf.java_class. 我当然可以在Java中定义一个接口,并通过intf.java_class将其用作API的接口参数。 However, for convenience, I'd like to be able to directly define the interface from JRuby code. 但是,为了方便起见,我希望能够直接从JRuby代码定义接口。

Update: Here's the Java API I want to invoke from JRuby: 更新:这是我想从JRuby调用的Java API:

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. Java API要求intf参数是接口,而不是类。 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.lang.reflect.proxy提供可以通过提供的接口访问的数据对象的集合。 Java's java.lang.reflect.proxy will only work with interfaces. Java的java.lang.reflect.proxy仅适用于接口。 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 如果我是从Java调用的,则可以通过以下方式定义数据

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. 并将LogRecord.class作为第一个参数传递给Query.execute方法。

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: 我不认为这是可以做到的,因为Java类必须从ruby接口继承,并且显然Java类不能从JRuby类继承:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM