1

I hava a class following:

MyClass implements Serializable, Iterable<MyAnotherClass> {
    snip
}

I made following codes to get "MyAnotherClass" class from an instance of MyClass.
These work well but I feel it's not cool because I'm using "instanceof" operator even getting "Type" of interfaces.
Does anyone have better idea without using instanceof operator?

Object instance = (Object)new MyClass();
Class<?> iteratorParamClass = null;
Type[] interfaceTypes = instance.getClass().getGenericInterfaces();
for (Type type : interfaceTypes) {
    if (type instanceof ParameterizedType) { // ★This is not cool.
        Type rawType = ((ParameterizedType) type).getRawType();
        if (Iterable.class == (Class<?>) rawType) {
            iteratorParamClass = (Class<?>) (((ParameterizedType) type).getActualTypeArguments())[0];
        }
    }
}

I am happy if the Type interface had a method like "Class<?> getConcreteClass()".

Yoshipi
  • 13
  • 3
  • I would argue that in general you should not be needing to do this. Instead, code to an interface and only use that interface in the general way for which it is intended. – Tim Biegeleisen Dec 23 '19 at 04:54
  • What are you trying to accomplish here? The point of polymorphism is to enable [coding to an interface](https://stackoverflow.com/q/383947/642706) while not caring about the underlying concrete implementation. Yet you seem to be trying to unravel that which polymorphism seeks to mask. Perhaps you can use an example, such as `Kennel implements Serializable, Iterable`. – Basil Bourque Dec 23 '19 at 05:10
  • I am developping a versatile API to handle any instances. So, ```Object instance = (Object)new MyClass();``` is just a sample. This API has to handle any class. – Yoshipi Dec 23 '19 at 06:18

0 Answers0