lundi 13 juin 2016

Receiving java class object in Python

I've Java .jar file which has several classes defined and there is python framework which intends to pick any class from it, instantiate it's object and invoke it's method. To do this I'm using py4j JavaGateway().

At python side:

    from py4j.java_gateway import JavaGateway
    gateway = JavaGateway()
    obj_rcvd = gateway.entry_point.getObj("pkg.in.jar", "className", java_list)
    boo = pkg.in.jar.className(obj_rcvd) 
"""
this typecast fails as python env doesn't know about pkg from jar. Can we import java's jar file in Python? Also if we can, do we really need to call JVM to get objects?  
"""

At Java side:

public static Object getObj(String pkgName, String className, List args) {
        Object obj = null;
        try {
             Class cls2 = Class.forName(pkgName + '.' + className);
             int num_of_args = args.size(); 
             Class[] cArg = new Class[num_of_args];
             Object[] cArg_val = new Object[num_of_args];
             /* code to parse args to fill cArg and cArg_val */
             Constructor ctor = cls2.getDeclaredConstructor(cArg);
             obj = ctor.newInstance(cArg_val);                                   
        }
        catch (ClassNotFoundException x) {
            x.printStackTrace();
        }
        /* other exception catchers */
        return obj; // this is general Object type, hence I need to typecast in python
    }

I tried returning actual class object from Java(hard-coded for one case for debugging) but it too doesn't get recognized in Python. Please suggest if this approach to invoke methods of java jar in python is feasible.





Aucun commentaire:

Enregistrer un commentaire