Question

I'm looking a way to check from Java, that some object is an instance of some Groovy class.

It's looks like it's impossible, due to compilation process, including Java class stubs generation, for each Groovy class. So, instanceof with Groovy class will return false.

In Watches window I can test it.

ModelNode.class = {java.lang.Class@4830}"class ModelNode"
component.getClass() = {java.lang.Class@3073}"class ModelNode"
component instanceof ModelNode = false

Obviously, there are two different classes. And Java see generated one. So, I'm looking a nice way to check some object against Groovy class.

I'v tried reflexion and getSuperclass() method, and it's looks like there are two absolutely different classes, derived from same superclass.

component.getClass().getSuperclass() = {java.lang.Class@871}"class javax.swing.tree.DefaultMutableTreeNode"
ModelNode.class.getSuperclass() = {java.lang.Class@871}"class javax.swing.tree.DefaultMutableTreeNode"

Moreover I can't cast anything after instanceof, due to similar reasons. So, I must be doing smth wrong.

Is there a way to use Groovy objects in Java. Without having Java-side interface for ech necessary from java code method.

P.S. Last sentence is about such solution.

In Java

interface A {
  foo();
}

assert(object instanceof B) // false;
((A)object).foo(); // fail
assert(object instanceof A) // true;
((A)object).foo(); // nice

In Groovy

class B extends SMTH implements A { ... }
Était-ce utile?

La solution

instanceof GroovyObject?

I created the following Java class:

import groovy.lang.GroovyObject;

public class A {
  public static void main(String[] args) {
    B b = new B();
    if (b instanceof GroovyObject) {
      System.out.println("b is a groovyobject");
      b.yeah();
    } else {
      throw new RuntimeException("b is not a groovyobject");
    }
  }
}

And the following Groovy class:

class B {
  def yeah() {
    println "hell yeah"
  }
}

With the following result:

$ javac -cp ~/groovy/embeddable/groovy-all-2.1.3.jar:. A.java 
$ java -cp ~/groovy/embeddable/groovy-all-2.1.3.jar:. A
b is a groovyobject
hell yeah
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top