سؤال

I'm dynamically running groovy scripts from scala. And there are some instances of some class passed to groovy scripts via setProperty(). For example, say you have a class named TestA and class TestB inherits class TestA. And you are passing an instance of class B to groovy script like this

setProperty("testB", testB) // testB is an instance of class TestB

and running the groovy script, I can access variables declared in TestB. but when I try to access variables of TestA, which is super class of TestB, the groovy gives an error saying " No such property for class".

I can still call methods of both TestA and TestB from the given instance. So if you just write setter and getter, I can access to TestA's variables but I don't want to do it.

Is there anyway to access TestA's variables without using setter/getter? like using Expando or something?

هل كانت مفيدة؟

المحلول

Since you don't want to write the getters/setters yourself (which would be ugly boilerplate in Scala), you can simply add the scala.reflect.BeanProperty annotation (or scala.reflect.BooleanBeanProperty) to any fields you'd like to access from another JVM language. This will give you a more accessible API.

@scala.reflect.BeanProperty // generates getStatus() and setStatus() methods
var status = ""

نصائح أخرى

Actually, after giving it more thought, you could simply access the accessor methods that Scala generates for itself. You may be able to access Scala's accessor methods from Groovy, but accessing the setter variable_$eq may look a bit weird.

[dlee@dlee-mac scala]$ cat Prop.scala 
class Prop {
  var variable = "foo"
  val constant = "bar"
}

[dlee@dlee-mac scala]$ scalac Prop.scala 

[dlee@dlee-mac scala]$ javap Prop
Compiled from "Prop.scala"
public class Prop extends java.lang.Object implements scala.ScalaObject{
    public java.lang.String variable();
    public void variable_$eq(java.lang.String);
    public java.lang.String constant();
    public Prop();
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top