2017-09-19 14 views
0

인터페이스 유형의 변수를 생성하고 JRuby에서 Implementing 클래스를 사용하여 객체를 인스턴스화하는 방법을 알고 싶습니다. 자바에서 현재 jRuby에서 인터페이스 유형의 변수 만들기

, 우리가 할

하는 MyInterface intrf = 새로운 ConcreteClass 같은();

어떻게 jRuby에서 동일한 작업을 수행합니까? 나는 아래에 있었고 MyInterface 메서드를 찾을 수 없다는 에러 메시지를 던졌습니다.

MyInterface intrf = ConcreteClass.new;

답변

0

먼저 MyInterface intrf = ConcreteClass.new은 유효한 Ruby가 아닙니다. MyInterface은 참조에 대한 유형 지정자가 아닌 상수입니다 (예 : 클래스에 대한 상수 참조). Ruby이므로 JRuby는 동적으로 입력됩니다.

두 번째로 JRuby 클래스 ConcreteClass을 작성하고 Java 인터페이스 MyInterface을 구현한다고 가정합니다. 여기서는 예를 들어 Java 패키지 'com.example'에 있습니다.

require 'java' 
java_import 'com.example.MyInterface' 

class ConcreteClass 
    # Including a Java interface is the JRuby equivalent of Java's 'implements' 
    include MyInterface 

    # You now need to define methods which are equivalent to all of 
    # the methods that the interface demands. 

    # For example, let's say your interface defines a method 
    # 
    # void someMethod(String someValue) 
    # 
    # You could implements this and map it to the interface method as 
    # follows. Think of this as like an annotation on the Ruby method 
    # that tells the JRuby run-time which Java method it should be 
    # associated with. 
    java_signature 'void someMethod(java.lang.String)' 
    def some_method(some_value) 
    # Do something with some_value 
    end 

    # Implement the other interface methods... 
end 

# You can now instantiate an object which implements the Java interface 
my_interface = ConcreteClass.new 

페이지 JRuby Reference 특히, 자세한 내용은 JRuby wiki를 참조하십시오.