From: Ype K. <yk...@xs...> - 2003-03-05 19:16:10
|
Johannes, >Hello community, > >I would like to know how to handle Java typecasts in Jython. For example, I >have a Java class ProxyGenerator that I want to use in Python. It has (a.a.) >the method newInstance. From Java you would use the class as follows ( just >notice the typecast): > >agencyProxy = (IAgentSystem)ProxyGenerator.newInstance(IAgentSystem.class, > agencyAddress.generateAgentSystemId(), >agencyAddress); > >I can't just do > >agencyProxy = ProxyGenerator.newInstance(IAgentSystem.class, > agencyAddress.generateAgentSystemId(), >agencyAddress) > > >in Jython because I get the error that None has no attribute 'newInstance'. This indicates the the name ProxyGenerator is bound to None in your jython code. Could it be that it is null in Java, ie. did you instantiate it? >Instead, I have created a wrapper class GetAgency in Java > >public class GetAgency { > > public static IAgentSystem getAgency(GrasshopperAddress agencyAddress) { > return (IAgentSystem) ProxyGenerator.newInstance(IAgentSystem.class, > agencyAddress.generateAgentSystemId(), >agencyAddress); > } >} > >Now, it works if I do the following in Jython: > >agencyProxy = GetAgency.getAgency(agencyAddress) > > >Does that mean that I always have to write a wrapper in Java to do the >typecast and call this wrapper from Jython? > > >Also, I have this problem when I want to write a class (an agent) in Jython >that is used by a Java system (an agency in my case): The init method of the >agent class is used for startup parameters. However, the parameters are >contained in an java.lang.Object array (Object[]) and must be casted back to >their original types. If I write the agent class in Java, it looks like >this: > > > public void init(Object[] args){ > try{ > queryNr = ((Integer)args[1]).intValue(); > path = new ArrayList(); > Object[] pathArray= (Object[])args[0]; > for (int i=0;i<pathArray.length;i++) path.add(pathArray[i]); > finalDestination= (String)args[2]; > }catch(Exception exc){ > System.out.println("Exception in agent creation: "+exc.toString()); > } > > > } > > >How do I do this in Jython? Do I also have to write Java wrapper >classes/methods for each type cast? I suppose that I have to bother about >the casts because I don't think that Jythonc will get the things right >automatically and it will probably confuse the JRE running the agency. Basically, in Jython you can skip casting: def init(self, args): try: self.queryNr = int(args[1]) self.path = args[0][:] self.finalDestination = args[2] except Exception, e: print 'Exception ... ' + str(e) Nice and compact. You probably don't even need the try/except. Have fun, Ype -- |