Unable to transfer object to shared without warning

I have a class defined as follows:

public class SizeCache<T extends Identifiable> implements Observer {}

Identifiable is simply an interface that defines several methods.

I have a method:

public T put(final T item) {}

This adds the item to the list and is usually called directly with an item of type T, but can come from Observer, so in my Observer I want to make sure that it is of type T.

However, I cannot write this:

public void update(Observable observable, Object data) {
if (data instanceof T) {}
}                   

As it tells me, I need to use its erasable recognition.

However, when I passed it to Identifiable

Identifiable dataItem = (Identifiable) data;

the put (dataItem) call fails with the put (T) method, which is not applicable to the arguments.

and if I go to the real type T

T dataItem = (T) data;

He warns me of an uncontrollable actor. How to fix it?

+4
3

, . Java , T - .

- Class<T> update. Class<T> , update. isInstance:

if (clazz.isInstance(data))

T, , @SuppressWarnings("unchecked") update.

+2

, . , , T, :

@SuppressWarnings("unchecked")

, Class<T> data :

dataClass.isInstance(data);

, dataClass , isInstance null, data null, NullPointerException.

+1

- , . , Class T instanceof casting:

public class SizeCache<T extends Identifiable> implements Observer {
    private final Class<T> tClass;

    public SizeCache(Class<T> tClass) {
        this.tClass = tClass;
    }

    public void update(Observable observable, Object data) {
        if (tClass.isInstance(data)) {
            put(tClass.cast(data));
        }
    }
}
0

Source: https://habr.com/ru/post/1523579/


All Articles