Κυριακή, 26 Σεπτεμβρίου 2010

How to retrieve the type of content used for a Collection

If you need to know what is defined for each generic type in your instance use the following piece of code

Code:
Method method = myClass.getMethod("getCalendars", null);
Type returnType = method.getGenericReturnType();
if (returnType instanceof ParameterizedType) {
ParameterizedType type = (ParameterizedType) returnType;
Type[] typeArguments = type.getActualTypeArguments();
for (Type typeArgument : typeArguments) {
Class typeArgClass = (Class) typeArgument;
System.out.println("typeArgClass = " + typeArgClass);
}
}

Comments:
1) myClass is the class that has a method named "getCalendars" which returns an instance of a class that uses generics.
2) You can try it by implementing a class that returns a "java.util.List"

Gadget

Αυτό το περιεχόμενο δεν είναι ακόμα διαθέσιμο μέσω κρυπτογραφημένων συνδέσεων.

LinkWithin

Blog Widget by LinkWithin

Mobile edition