0

Can I call java method with interface as parameters? When I call java method can I cast it into interface before I use it as paramaters?

Here's my sample code.

// Java code
interface IFace {
  String message();
}
class A implements IFace {
  @Override message () { return "Hello A!"};
}
class B implements IFace {
  @Override message () { return "Hello B!"};
}
class PrintHello {
  static void print (IFace msg) {
    if (msg instanceof A) { ... } else { ... }
  }
}

; Clojure code

(def a (A.))
(. PrintHello (print a))
2
  • 1
    The code you've posted should work - what problem are you having? Commented May 5, 2020 at 20:34
  • (PrintHello/print a) Commented May 5, 2020 at 22:42

2 Answers 2

0

Changed Java code works for me (see comments):

public interface IFace {
    String message();
}

// Class should be public
public class A implements IFace {
    @Override
    public String message() {
        return "Hello A!";
    }
}

// Class should be public
public class B implements IFace {
    @Override
    public String message() {
        return "Hello B!";
    }
}

public class PrintHello {
    // Method should be public
    static public void print (IFace msg) {
        msg.message();
    }
}
(def a (A.))
(PrintHello/print a)
Sign up to request clarification or add additional context in comments.

Comments

-1

Here is a slightly cleaner version of your code:

~/expr/demo > d **/*.java   
-rw-rw-r-- 1 alan alan 136 May  5 13:42 src/java/demo/Bart.java
-rw-rw-r-- 1 alan alan 120 May  5 13:42 src/java/demo/Homer.java
-rw-rw-r-- 1 alan alan  62 May  5 13:37 src/java/demo/Msg.java

> more **/*.java

::::::::::::::
Msg.java
::::::::::::::
package demo;
public interface Msg {
  public String msg();
}


::::::::::::::
Bart.java
::::::::::::::
package demo;
public class Bart implements Msg {
  public Bart() {}
  public String msg() {
    return "Don't have a cow, man!";
  }
}

::::::::::::::
Homer.java
::::::::::::::
package demo;
public class Homer implements Msg {
  public Homer() {}
  public String msg() {
    return "Doh!";
  }
}

Clojure code:

(ns tst.demo.core
  (:use demo.core tupelo.core tupelo.test)
  (:import [demo Msg Homer Bart]))

(dotest
  (let [homer (Homer.)
        bart  (Bart.)]
    (spyx (.msg homer))
    (spyx (.msg bart))))

with result:

-------------------------------
   Clojure 1.10.1    Java 14
-------------------------------

lein test tst.demo.core
(.msg homer) => "Doh!"
(.msg bart) => "Don't have a cow, man!"

Please see this template project and the documentation resources list.

1 Comment

I want to call it from static method. ex. in java add class PrintHello on package demo, and create static method with parameter (Msg).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.