Search code examples
javareflectioninterfacesdkinternals

Why java.lang.Class doesn't implement java.lang.reflect.Member interface?


I'm working on a Package Browser in browser in Java and trying to write a generic method which can handle all members of the class - basically collecting string representation of them, choosing an image and displaying it in a tree view.

For all Members (Field, Method, Constructor) it has been working great - they all have getName() and isSynthetic() which allows me to treat them in the same way because that's all I need.

But Class is special - even though it has all the methods of that interface, it doesn't technically implement it!.

And to handle it I need a special-case-method or do an instanceof checks, which is not very clean.

So, i guess, this is more of a philosophical question - why is that? Because classes are not considered to be "proper" members of classes and instead are nested? Or because of something else?

Please shine the light on this topic!

I tried to treat objects of type Class<?> as if they implemented interface Member.


Solution

  • I think the answer should be found in getDeclaringClass.

    From Member:

    Returns the Class object representing the class or interface that declares the member or constructor represented by this Member.

    From Class:

    If the class or interface represented by this Class object is a member of another class, returns the Class object representing the class in which it was declared. This method returns null if this class or interface is not a member of any other class. If this Class object represents an array class, a primitive type, or void,then this method returns null.

    That possible null is the main difference. Instances of Member are not allowed to return null, instances of Class are. If Oracle would change the specification of Member.getDeclaringClass to allow null return values, that could break existing code. They can fix those occurrences in the JDK itself, but not in third party code.