How to view imported classes from py4j gateway

3.4k views Asked by At

Consider the following py4j gateway init code:

from py4j.java_gateway import java_import, JavaGateway, GatewayClient
gateway = JavaGateway(GatewayClient(port=gateway_port), auto_convert=False)

java_import(gateway.jvm,'org.apache.hadoop.hbase.client.*')
java_import(gateway.jvm,'org.apache.hadoop.hbase.filter.*')

What code could be invoked on the gateway to view the imports it contains - and/or validate that a given class were available? i.e. something like:

print("Client class: %s\n" %gw.get_class('org.apache.hbase.client.Client').get_name())
1

There are 1 answers

0
Barthelemy On BEST ANSWER

There is no public API to retrieve all imported classes, but you can open a feature request.

In the meantime, you can use the internal API, which may change in the future, but this part of the internal API has been stable since early releases:

from py4j.java_gateway import java_import, JavaGateway, JavaObject
from py4j.protocol import DEFAULT_JVM_ID

def get_imports(gateway):
    java_jvm_view = JavaObject(DEFAULT_JVM_ID[1:], gateway._gateway_client)
    imports = list(java_jvm_view.getSingleImportsMap().values()) + list(java_jvm_view.getStarImports())
    return imports

java_gateway = JavaGateway()
java_import(gateway.jvm, "java.util.Collection")
java_import(gateway.jvm, "java.sql.*")
java_import(gateway.jvm, "java.util.ArrayList")
imports = get_imports(gateway)
# [u'java.util.ArrayList', u'java.util.Collection', u'java.lang', u'java.sql']