2010-12-27 16 views
1

私はBar型のプロパティであるFooクラスを持っています。ネストされたプロパティのメソッドを取得するにはどうすればよいですか?

public class Foo { 
    public Bar getBar() { 

    } 
} 

public class Bar { 
    public String getName(); 
} 

Foo.classと「bar.name」を使用して、あなたにBarのnameプロパティのjava.lang.reflect.Methodオブジェクトを取得するヘルパークラスやメソッドはありますか?

ありコモンズ々BeanUtilsでPropertyUtilsと呼ばれるクラスがあるが、そのgetPropertyDescriptor()Objectのインスタンスではなく、Classインスタンスのために動作します。

私はそれを実装することはまったく難しくありませんが、すでに利用可能なものを活用したいと思います。

また、私がMethodオブジェクトを必要としているという事実は、悪い設計の結果ではありません。私が取り組んでいるのは、かなりJavaBeansエディタです。

ありがとうございます!

+0

"public Bar getBar()"を意味しましたか? –

+0

私は彼がやったと思っていますが、そうでなければ質問は意味をなさないでしょう。 – OscarRyz

答えて

1

Commons BeanUtilsでは、PropertyUtils.getPropertyDescriptors()Classを入力として受け取り、PropertyDescriptorの配列を返します。

bar.nameなどの「ネスト」名が返されるかどうかはわかりませんが、そうでない場合は、結果を再帰的に処理したり、ネストされた名前のリストを作成したりしないでください。

世界は本当に別のJavaBeansエディタを本当に必要としますか?

+0

Hehは、JavaBeansエディタではなく、JavaBeansエディタからいくつかの概念を借りているWebフォームです。 –

1

私はMVELまたはOGNLに行き、「メソッドオブジェクトが必要です」という要件をスキップします。

1

ここでネストされたサポートのために行く: 使用ケースに応じて、取得されたクラスをキャッシュすることができます。たとえば、重いフィルタリングが使用されるデータ可能なクラッドアプリケーションの場合。

/** 
* Retrieves the type of the property with the given name of the given 
* Class.<br> 
* Supports nested properties following bean naming convention. 
* 
* "foo.bar.name" 
* 
* @see PropertyUtils#getPropertyDescriptors(Class) 
* 
* @param clazz 
* @param propertyName 
* 
* @return Null if no property exists. 
*/ 
public static Class<?> getPropertyType(Class<?> clazz, String propertyName) 
{ 
    if (clazz == null) 
     throw new IllegalArgumentException("Clazz must not be null."); 
    if (propertyName == null) 
     throw new IllegalArgumentException("PropertyName must not be null."); 

    final String[] path = propertyName.split("\\."); 

    for (int i = 0; i < path.length; i++) 
    { 
     propertyName = path[i]; 
     final PropertyDescriptor[] propDescs = PropertyUtils.getPropertyDescriptors(clazz); 
     for (final PropertyDescriptor propDesc : propDescs) 
      if (propDesc.getName().equals(propertyName)) 
      { 
       clazz = propDesc.getPropertyType(); 
       if (i == path.length - 1) 
        return clazz; 
      } 
    } 

    return null; 
} 
関連する問題