Type of Class

Stephen Colebourne scolebourne at joda.org
Thu Feb 20 17:38:52 UTC 2014


In JDK 5, three methods were added to java.lang.Class [1]
- isAnonymousClass()
- isLocalClass()
- isMemberClass()

Unfortunately, these do not cover the complete range of possible types of class.

Would it be reasonable to add the following methods:
- isNestedClass()
- isInnerClass()
- isTopLevelClass()

While JVM/spec experts may know the difference, it is a surprisingly
tricky area. For example, the current isMemberClass() method could do
with much better Javadoc to explain what a member class actually is
(as it seemed hard to google).

FWIW, I was just trying to tell the difference between a nested class
and an inner class, in order to determine which classes can be
instantiated without reference to a surrounding object. The answer
seems to be (cls.isMemberClass() &&
Modifiers.isStatic(cls.getModifiers()) which is not the most obvious
code.


In addition, I suffered from the absence of an isNormalClass() -
probably a better name for this.

Currently, you can determine if a class is an interface, annotation,
primitive or array, leaving the "normal" case as a quadruple negative.
This leaves such a user-written method vulnerable to any new type of
class that gets added in a future JDK:

boolean isNormalClass(Class cls) {
  return !cls.isInterface() && !cls.isAnnotation() &&
!cls.isPrimitive() && !cls.isArray();
}

Stephen
[1] https://blogs.oracle.com/darcy/entry/nested_inner_member_and_top



More information about the core-libs-dev mailing list