Answer the question
In order to leave comments, you need to log in
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;
}
}
Answer the question
In order to leave comments, you need to log in
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.
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 questionAsk a Question
731 491 924 answers to any question