Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No interface word before interface Comparable

It is detail, but I want to know why this happens.

Exemplary code:

Class klasa = Enum.class;
for(Type t : klasa.getGenericInterfaces())
   System.out.println(t);

Output o the program:

java.lang.Comparable<E>
interface java.io.Serializable

Why on the output there is no interface word before java.lang.Comparable<E>. It is interface, yes?

In my opinion output should be:

**interface** java.lang.Comparable<E>
interface java.io.Serializable

Comparable is specially treated?

like image 582
Pawel Avatar asked Oct 09 '13 09:10

Pawel


2 Answers

What happens is that you get two different subclasses of java.lang.reflect.Type; one that is a generic type (probably j.l.r.ParameterizedType), and one that is a specific (non-generic) interface type (a j.l.Class<?>).

What do you want to do with that information, and why?

like image 38
Tassos Bassoukos Avatar answered Sep 28 '22 14:09

Tassos Bassoukos


The toString method of ParametrizedTypeImpl(the internal Type of Comparable), indicates that "interface" is not outputted in any case:

public String toString() {
    StringBuilder sb = new StringBuilder();

    if (ownerType != null) {
        if (ownerType instanceof Class)
            sb.append(((Class)ownerType).getName());
        else
            sb.append(ownerType.toString());

        sb.append(".");

        if (ownerType instanceof ParameterizedTypeImpl) {
            // Find simple name of nested type by removing the
            // shared prefix with owner.
            sb.append(rawType.getName().replace( ((ParameterizedTypeImpl)ownerType).rawType.getName() + "$",
                                     ""));
        } else
            sb.append(rawType.getName());
    } else
        sb.append(rawType.getName());

    if (actualTypeArguments != null &&
        actualTypeArguments.length > 0) {
        sb.append("<");
        boolean first = true;
        for(Type t: actualTypeArguments) {
            if (!first)
                sb.append(", ");
            if (t instanceof Class)
                sb.append(((Class)t).getName());
            else
                sb.append(t.toString());
            first = false;
        }
        sb.append(">");
    }

    return sb.toString();
}

In the toString method of Class, on the other hand, "interface" is clearly output if the class is an interface.

public String toString() {
    return (isInterface() ? "interface " : (isPrimitive() ? "" : "class "))
        + getName();
}
like image 120
Pratik Shelar Avatar answered Sep 28 '22 15:09

Pratik Shelar