22.3 Writing your own Functors in Java

Due to recent advances in SWIG (the program used to produces Python and Java wrappers), users can now derive their own functors from the C++ base classes: OEUnaryAtomPred, OEUnaryBondPred, OEUnaryConfPred, etc.

At the least the derived class must provide a constCall method that returns true or false for any passed in object. Also, in order to create composite predicates, the programmer must provide an implementation of CreateCopy. In this simplest case, just a call to the default contructor works. However, if you design more elaborate predicates, that include their own internal "state", make sure to also implement a copy constructor and use that for the internal implementation inside CreateCopy

The following example shows a user defined functor which screens for atoms whose atomic mass is greater than 15.

 1 /**************************************************************
 2  * Copyright 2005,2008 OpenEye Scientific Software, Inc.
 3  *************************************************************/
 4
 5 import openeye.oechem.*;
 6
 7 public class UserDefinedPredicate {
 8   private class WgtGT15 extends OEUnaryAtomPred {
 9     public boolean constCall(OEAtomBase atom) {
10       return (atom.GetAtomicNum() > 15);
11     }
12     public OEUnaryAtomBoolFunc CreateCopy() {
13       OEUnaryAtomBoolFunc copy = new WgtGT15();
14       copy.swigReleaseOwnership();
15       return copy;
16     }
17   }
18
19   public void ShowAtoms() {
20     OEMol mol = new OEMol();
21     oechem.OEParseSmiles(mol, "c1c(O)c(O)c(Cl)cc1CCCBr");
22     oechem.OETriposAtomNames(mol);
23     for (OEAtomBaseIter aiter=mol.GetAtoms(new WgtGT15());aiter.hasNext();) {
24       System.out.println(aiter.next().GetName());
25     }
26   }
27   public static void main(String argv[]) {
28     UserDefinedPredicate app = new UserDefinedPredicate();
29     app.ShowAtoms();
30   }
31 }

Listing:22.2 User defined predicates can be simple