Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Reflection: (Type) field.get(object) - unchecked cast

Following code retrieves the value of a field using the Reflection API. As you can see in the provided image, this generates an unchecked cast warning. The warning can be suppressed using @SuppressWarnings("unchecked"). I was wondering if there is an alternative to this though?

Update: KeyType is a generic. So KeyType.class.cast(object); wouldn't work due to type erasure.

private K getId(Field idField, V o) {
    K id = null;
    try {
        idField.setAccessible(true);
        id = (K) idField.get(o);
    } catch (IllegalAccessException ignored) {
        /* This never occurs since we have set the field accessible */
    }
    return id;
}

Unchecked cast warning


Solution: Seems like the SuppressWarnings annotation IS the way to go here.. thanks for your time guys.

Solution

like image 568
Jasper Catthoor Avatar asked Jul 16 '26 19:07

Jasper Catthoor


1 Answers

The Class method cast doesn't require the @SupressWarnigns even though it still can throw ClassCastException.

KeyType keyType = KeyType.class.cast( idField.get(o) );

You can - since at that location you should know the generic paramter(s) - proceed like this:

private static class ListInteger extends ArrayList<Integer>{}

Object obj = new ArrayList<Integer>();
ListInteger test = ListInteger.class.cast(obj);

Once you have an object of class KeyType you can, of course,

KeyType keyTypeX = ...; // not null

KeyType keyType = keyTypeX.getClass().cast( obj );

There are alternatives, although the @SuppressWarnings isn't so bad - try to limit it to an declaration+assignment, don't put it on the method.

like image 57
laune Avatar answered Jul 18 '26 09:07

laune



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!