jeudi 30 avril 2020

Getting the type of Interface in Java

Currently, I am learning Java on Hyperskill, there is one question that I need help and clarification.

You need to implement method getComparatorType(Class) in ComparatorInspector class. The method should examine provided class and return Type object that corresponds to the type parameter that parameterizes Comparable interface the class implements. Consider the example:

class MyInt implements Comparable<Integer> {
    // Implementation omitted 
}

// Method to implement
Type type = ComparatorInspector.getComparatorType(MyInt.class);

System.out.println(type.getTypeName());
// prints: java.lang.Integer since MyInt implements Comparable with Integer parameter type

The method should:

  1. Return type parameter for Comparable interface class implements
  2. Return null if Comparable interface does not have type parameter
  3. Should not produce compile-time warnings
  4. Compile-time error should arise if class not implementing Comparable is provided as input value
  5. No 'rawtype' warnings should remain or be suppressed
  6. Method getComparatorType should be generic You are free to correct method's type signature if needed.

My code so far:

public static <T extends Comparable<?>> Type getComparatorType(Class<T> clazz) {
        // Add implementation
        // Print type name
        if (clazz.getGenericInterfaces().length == 0) {
            return null;
        }
        Type t = null;
        Type[] types = clazz.getGenericInterfaces();
        for (Type type : types) {
            if (type instanceof ParameterizedType) {
                t = ((ParameterizedType) type).getActualTypeArguments()[0];
            }
        }
        return t;
    }

I think the only problem I have here is the parameter type in the method signature. As far as I understand, the type in the method signature will be used in the parameter of this method and this type T should extend Comparable. But there is a flaw somewhere in the method signature, hope someone can help. I'm much appreciated.





Aucun commentaire:

Enregistrer un commentaire