0

jythonはインテリジェントであり、(単純な)ゲッター/セッターメソッドのプロパティを自動的に作成しようとしているため、今日jythonでJavaオブジェクトを使用する際に問題が発生しました-メソッドごとに、先頭get/set削除された次の文字が小文字に変換されたフィールドが作成されます:

//java code
class MyClass {
    public List<Thing> getAllThings() { ... }
    public List<Thing> getSpecificThings(String filter) { ... }
    public void setSomeThing(SomeThing x) { ... }
    [...]
}

#jython code
obj = MyClass()
hasattr(obj, "allThings") #-> True
hasattr(obj, "specificThings") #-> False because getSpecificThings has a param
hasattr(obj, "someThing") #-> False BUT
"someThing" in dir(obj)   #-> True

最後の行は、ここで私の問題を要約しています-の結果にdirは、これらのフィールドが含まれています(obj.classの代わりに実行された場合でもobj)。オブジェクトで呼び出し可能なすべてのメソッドのリストが必要です。これは、基本的にこれらのプロパティがなく、アンダースコアで始まるものdirをすべて除外するようにフィルタリングされた結果です(これの目的は、一部のPythonクラスを自動的に変換することです) java.lang.Objectjavaに相当するもの、たとえばマップへのdicts)。理論的には__dict__、それらを含まないものを使用できますが、これは、基本クラスも再帰的に評価する必要があることを意味します__dict__。これは避けたいと思います。私が現在行っているのは、属性が実際に存在するかどうかを確認してから、属性が存在するかどうかを確認することです。argslistdir属性(メソッドであることを意味します)。これは、生成されたプロパティを除くすべてのエントリに当てはまります。

for entry in dir(obj):
    #skip things starting with an underscore or inherited from Object
    if entry.startswith("_") or entry in dir(java.lang.Object): continue
    #check if the dir entry is a fake setter property
    if not hasattr(obj, entry): continue
    #check if the dir entry has an argslist attribute (false for getter props)
    e = getattr(obj, entry)
    if not hasattr(e, "argslist"): continue
    #start actual processing of the entry...

このアプローチの問題は、問題のオブジェクトがBeanへのインターフェースであり、getSomethingメソッドが通常データベースからデータをフェッチするgetattrため、プロパティの呼び出しがDBへのラウンドトリップを行い、数秒かかり、大量のメモリを浪費する可能性があることです。

jythonがこれらのプロパティを生成するのを止めることはできますか?そうでない場合、最初にプロパティにアクセスせずにプロパティを除外する方法を誰かが知っていますか?私が考えることができる唯一のことは、 /dirという名前のメソッドが含まれているかどうかを確認することでしたが、これはハックのようであり、誤検知を生成する可能性があり、回避する必要があります。getset<property>

4

1 に答える 1

0

答えは予想よりも簡単でした。hasattrプロパティのaはTrueオブジェクトインスタンスFalse用ですが、問題のget-methodが静的でない場合はobjectsクラス用です。クラスでメソッドを実行できないため、クラスにはプロパティがありません。更新されたループは次のようになります。

for entry in dir(obj):
    #skip things starting with an underscore or inherited from Object
    if entry.startswith("_") or entry in dir(java.lang.Object): continue
    #check if the dir entry is a fake property
    if not hasattr(obj.class, entry): continue
    #check if the dir entry has an argslist attribute (false if not a method)
    e = getattr(obj, entry)
    if not hasattr(e, "argslist"): continue
    #start actual processing of the entry...
于 2012-10-12T11:43:41.983 に答える