Domanda

I have a class with a getter and setter:

class A
{
  private Set<Offers> offers;

  public Set<Offers> getOffers(){
    return offers;
  }

  public void setOffers(Set<Offers> offers){
    this.offers = offers;
  }

}

Now I wanted to get the size() of the offers using Apache Commons PropertyUtils:

PropertyUtils.getProperty(myAInstance, "offers.size");

This should basically do the same as:

myAInstance.getOffers().size();

But using the PropertyUtils doesn't work and gives me a:

java.lang.NoSuchMethodException: Unknown property 'size' on class 'class java.util.LinkedHashSet'

Using PropertyUtils to all getters and setters on other objects is working fine.

I suspect it is because the size() method of a Collection is not following the getXXX and setXXX bean convention.

Is there another way to use PropertyUtils / or BeanUtils (or anything else from Apache Commons) to call the size() method of my collection?

Thanks Christoph

È stato utile?

Soluzione

PropertyUtils is named "PropertyUtils" for a reason. It works on the java beans conventions. The "size()" method does not conform to that convention, so you can't refer to it as a property.

Perhaps you're better of with a something like MVEL or GroovyScript which supports both property navigation and function invocation. Here's a sample for mvel which should work

Integer size = (Integer) MVEL.eval("offers.size()", instanceOfA);

Give it a try.

Altri suggerimenti

A way around it (couldn't get it to work) + I concur with Dave 'Not entirely clear why you'd want to'

add this to your A class

public int getOfferSize(){
    return offers == null ? 0 : offers.size();
}

Then use

PropertyUtils.getProperty(myAInstance, "offerSize");

Not entirely clear why you'd want to, although it does offer some thin wrappers around the reflection API.

You'll want to use the MethodUtils class, specifically one of the invokeExactMethod or invokeMethod variants.

You can do this through good old reflection directly, avoiding any libraries.

First, you get the getter:

Method get = A.class.getDeclaredMethod("getOffers");

Now you invoke the getter and obtain the object that represents the set. Then you create a new Method representing the size method defined in Set:

Object setFromA= get.invoke(yourAObject);
Method size = Set.class.getDeclaredMethod("size");

Finally, you cast the method on setFromA and get the size, casting your setFromA object to the required type:

Integer listSize = (Integer) size.invoke(get.getReturnType().cast(setFromA));
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top