1

In Apache Commons BeanUtil, how to get a type inside a list ? for example

class Track {
   List<Actor> actorList = new ArrayList<Actor>();
}

System.err.println(PropertyUtils.getPropertyType(trackBean, "actorList"));
// it should give me Actor instead of java.util.List

Thanks.

skaffman
  • 398,947
  • 96
  • 818
  • 769
user595234
  • 6,007
  • 25
  • 77
  • 101
  • All generic types are subject to type erasure, so at runtime there is no way Java knows that this is a list of actors. I do not know bean utils, but for this to work this must be solved at compile time. – Edwin Dalorzo Apr 10 '11 at 17:49
  • Duplicate of: http://stackoverflow.com/questions/1127923/specifying-generic-collection-type-param-at-runtime-java-reflection – Will Iverson Apr 10 '11 at 20:49

1 Answers1

4

I don't know if it's possible with beanutils. But you can do so with reflection.

Field field = Track.class.getDeclaredField("actorList");
ParameterizedType pt = (ParameterizedType) field.getGenericType();
Class clazz = (Class) pt.getActualTypeArguments()[0];

You will perhaps need a few check above (whether you can cast, whether the actual type arguments exist, etc), but you get the idea.

Type information is erased at runtime, unless it is structural - e.g. the type argument of a field, or of class.

Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140