3

How can I determine if a java.lang.Class object represents a class?

Other java types can be determined by methods like isEnum(), isAnnotation(), isInterface(). I'm missing a method for the class type.

3
  • You can make your world easier by using a marker interface and check against that. When you are searching for something you will search for something that is a little bit more specific than just a class. Commented Apr 14, 2017 at 11:14
  • 3
    This is not an omission, because all of these things are classes. I'm not sure why you want to make such fine distinction, but I am 100% sure that there are multiple, different, context-dependent ways to make such a distinction (do abstract classes count? Do interfaces, all of whose methods have defaults, count?) If you mean "a class but not an interface, enum, or record", you can eliminate these yourself, but first you have to decide what you mean by "class", and why you are even making such find distinctions. Commented Jun 19, 2022 at 20:17
  • 3
    (continued) For example, if you want to know "can I use this as a superclass", you also have to check finality (and also accessibility of the constructors.) If you want to know "will I ever see an object whose getClass returns this class, you have to eliminate abstract classes. Etc etc. It's not really a very well-defined question; you have to refine it yourself, and the JDK isn't going to guess at what you mean. Commented Jun 19, 2022 at 20:19

1 Answer 1

4

I think it's a matter of elimination:

if (!c.isEnum() && !c.isInterface() && !c.isArray() && !c.isAnnotation() && !c.isPrimitive()) {
    // It's a class
}

...which isn't very satisfying, as you have to revisit that definition when new features are added to Java (like enums, annotations, ...).

Sign up to request clarification or add additional context in comments.

4 Comments

if it's a class, we probably should make sure that it is a top-level class throwing away inner, local, anonymous ones.
@AndrewTobilko: It depends on what the OP wants to consider a class. Member classes and local classes and anonymous classes are all classes. :-)
"...which isn't very satisfying, as you have to revisit that definition when new features are added to Java (like enums, annotations, ...).". True. But the flip-side is that you would probably need to do that anyway ... so that your code can deal with this new Java feature.
The c.isAnnotation() test is obsolete, as annotations have been ruled out by !c.isInterface() already.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.