M
M
MaxLich2018-02-19 12:29:37
Java
MaxLich, 2018-02-19 12:29:37

How to determine that a generic class is typed with the desired concrete type?

Hello. Sometimes there is a need to check whether an object is a representative of some generic class, parameterized with concrete types. While I usually do not do such a check, I only check that the object is a representative of the generic class itself. But a generic class can be parameterized in each specific case with some type of its own. If the types don't match, I'll get an error. How to check that types match?
Code example:

public abstract class BaseComboBox<T> extends JComboBox<ComboboxItem<T>> {
//некоторый код
    @Override
    public ComboboxItem<T> getSelectedItem() {
        Object selectedItem = super.getSelectedItem();
        if (selectedItem == null)
            return null;
        else {
            if (selectedItem.getClass() == ComboboxItem.class) { // (1)
                return (ComboboxItem<T>) selectedItem; // (2)
            } else {
                return null;
            }
        }
    }
//некоторый код
}

public class ComboboxItem<T> {
    private String caption;
    private T value;

    public ComboboxItem(String caption, T value) {
        this.caption = caption;
        this.value = value;
    }

    @Override
    public String toString() {
        return caption;
    }

    public String getCaption() {
        return caption;
    }

    public T getValue() {
        return value;
    }
}

In this example, in line (1), I just check that the classes match, but do not check that the type in angle brackets matches. In (2) I am casting, and there may be an error here if the types are different. (Although in this case, the types will always match, in other places, similar code can cause an exception)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey Gornostaev, 2018-02-19
@MaxLich

First, generics are compiler-only instructions. They are not in the bytecode at all and the virtual machine knows nothing about them. Second, your code violates OOP principles. As soon as you need type checking at runtime, know that you have written bad code.

Y
Yerlan Ibraev, 2018-02-19
@mad_nazgul

The problem is that generics in Java up to and including 1.8 exist only at compile time.
It is problematic to find out the generic type in a legal way at runtime.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question