pandita
pandita

Reputation: 21

Class cannot be cast to ParameterizedType

public class FrontUtil<T> {

    public List<Map<String, String>> tableGen(List<Map<String, String>> theads, List<T> tbodys){


        List<Map<String, String>> frontList = null;

        for (T t : tbodys) {
            *Class<T> clazz =(Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];*
            for (Map<String, String> title : theads) {
                try {
                    Field field = clazz.getDeclaredField(title.get("columnClass"));
                    PropertyDescriptor pd = new PropertyDescriptor(field.getName(), clazz);
                    Method getMethod = pd.getReadMethod();
                    String content = getMethod.invoke(t).toString();
                    Map<String, String> temp = new HashMap<String, String>(0);
                    temp.put(title.get("columnName"), content);
                    frontList.add(temp);
                }  catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }

        return frontList;
    }
}

the stack:

java.lang.ClassCastException: java.lang.Class cannot be cast to java.lang.reflect.ParameterizedType
    *****FrontUtil.tableGen(FrontUtil.java:19)
    *****action.MaterialFactoryAction.list(MaterialFactoryAction.java:78)
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

I would like to get the Actual class of T though

Class<T> clazz =(Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];

but it can't work . Any suggestion would be appreciated,thanks.

Upvotes: 0

Views: 1366

Answers (1)

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 279970

The answer is: you can't. Because of type erasure that information no longer exists at run time.

Pass in a Class argument when you create your FrontUtil instance.

private Class<T> clazz;
public FrontUtil(Class<T> clazz) {
    this.clazz = clazz;
}

Then use that Class object wherever you need it.

Upvotes: 1

Related Questions