how is scala type casting done in py4j?

1.6k views Asked by At

Is there a way to do type casting like it is done is scala/java when using py4j to trigger jvm?

Basically, I would like to translate this:

someOtherTypeInstance.asInstanceOf[RDD[Any]]

Into something like:

someOtherTypeInstance = gateway.jvm.getSomeOtherTypeInstance()
someOtherTypeInstance.asInstanceOf(gateway.jvm.RDD[Any]) // don't know how to deal with generics
1

There are 1 answers

0
Barthelemy On BEST ANSWER

Py4J does not generally require type casting because of its heavy use of reflection.

If you call a method on an object, Py4J will use the JVM reflection facilities to find this method in the class hierarchy of the object no matter what the advertised type of the object is. Similarly, when you pass an object to a method, Py4J will try to find the closest method signature by inspecting the class hierarchy and implemented interfaces of the object.

For example, this code is perfectly valid in Py4J:

// Java code
public class TestTypes {
    public void method1(Foo param1) {}

    public Object getObject() { new Foo() }
}

// Python code
myJavaObject = java_gateway.jvm.TestTypes()
obj = myJavaObject.getObject()
// no need for type casting
myJavaObject.method1(obj)

If you need type casting for other scenarios (I don't know much about Scala), you should fill a feature request.