2010-12-27 4 views
1

나는 Bar 타입의 속성 인 Foo 클래스를 가졌다.중첩 된 속성의 메소드를 얻으려면 어떻게해야합니까?

public class Foo { 
    public Bar getBar() { 

    } 
} 

public class Bar { 
    public String getName(); 
} 

Foo.class와 "bar.name"을 사용하여, 당신에게 Bar의 이름 속성의 java.lang.reflect.Method 객체를 가져옵니다 헬퍼 클래스 또는 방법이 있습니까?

는 가공 BeanUtils에서 PropertyUtils라는 클래스가 있지만 getPropertyDescriptor()Object 경우,하지 Class 인스턴스를 사용할 수 있습니다.

하나를 구현하는 것이 전혀 어렵지는 않지만 이미 사용할 수있는 것을 활용하고 싶습니다.

또한 Method 객체가 필요하다는 사실은 나쁜 디자인 (희망하지 않음)의 결과가 아닙니다. 내가하고있는 일은 자바 빈즈 편집기 다.

감사합니다!

+0

"public Bar getBar()"? –

+0

나는 그랬 겠지 그렇지 않으면 질문이 의미가 없다. – OscarRyz

답변

1

Commons BeanUtils에서 PropertyUtils.getPropertyDescriptors()Class을 입력으로 받아 PropertyDescriptor의 배열을 반환합니다.

bar.name과 같이 "중첩 된"이름을 반환할지 여부는 알 수 없지만 결과가 너무 복잡해서 중첩 된 이름 목록을 구성하기가 너무 어려워서는 안됩니다.

세상에는 또 다른 JavaBeans 편집기가 정말로 필요합니까?

+0

Heh, 그것은 자바 빈즈 편집자가 아니라 자바 빈즈 편집자의 개념을 빌려주는 웹 폼이다. –

1

MVEL 또는 OGNL을 사용하고 "메서드 개체가 필요합니다"요구 사항을 건너 뜁니다.

1

여기서 중첩 된 지원을 위해 이동합니다. 사용 사례에 따라 검색된 클래스를 캐시 할 수 있습니다. 예를 들어 무거운 필터링이 사용되는 datatable crud 어플리케이션에서.

/** 
* 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; 
} 
관련 문제