Skip to main content

Equivalent of Class.cast for Collections etc.

No replies
Joined: 2006-01-07

Sometimes in generics we have the Class object of the template variable type to hand. This allows the programmer to get arround the "deletion" effect. In such case, for example, we have Class.cast() which saves us a warning.

I find, sometimes, I could do with the same thing for generic collections.

Suppose, for example, Collections defined an extra method

<br />
List unmodifiableList(List<? extends T> list, Class clazz);<br />

It wouldn't even need to have extra code.

For example, at the moment I have:

<br />
    public  List getAll(Class clazz) {<br />
        if(clazz.equals(Manager.class))<br />
            return (List)(splitManagers);<br />
        else {<br />
...<br />

(splitManagers is a List and Manager extends TreeItem).

There's no avoiding that unchecked warning on the return statement.

If I was returning a simple object of class T I could use clazz.cast();