Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test that a type declared as "public class" is a class using java.lang.Class?

Tags:

java

java.lang.Class has methods to test if a given type is:

  • isAnnotation
  • isArray
  • isEnum
  • isInterface
  • isPrimitive

but how does one test that an object of type Class (instanceof Class is true) represents a declared, non-abstract class rather than in interface, enum, primitive, array, etc. For example:

package org.acme;

public class ACME {

      public ACME() {

      }

      public static void main(String[] args) {
        Class clazz = Class.forName("org.acme.ACME");
       // Expected I could use a clazz.isClass().
      }
}

I was looking for a isClass method, but there isn't.


Update

I see the confusion generated by my question - while some people got my question.

I did some further research and found out that in .NET

http://msdn.microsoft.com/en-us/library/system.type.isclass.aspx,

there this is a isClass member and I was looking for a similar method in java.lang.Class.

I now know that the equivalent in Java is to test for all the other isXXX methods to find out that it's not a class.

like image 359
Jack G. Avatar asked Jun 19 '13 17:06

Jack G.


2 Answers

It seems there's a disconnect in your question. Everything is a class (except primitives - the isPrimitive() method actually means the class is an autobox type).

Class clazz = Class.forName("org.acme.ACME");
// Expected I could use a clazz.isClass().

That would be redundant. You already know it's a class. Because you have an instance of Class.

It would appear that for some reason you would like to know it's not any of the types of classes the methods you list tell you, in which case you'd simply do a check to negate those options:

if (!clazz.isAnnotation() &&
    !clazz.isArray() /* && ... etc */ ) 
{

    // Not any of those things.

}
like image 175
Brian Roach Avatar answered Sep 28 '22 17:09

Brian Roach


Class objects are singletons. Therefore, if you have an instance of any type, you can test that it is an exact class instance using:

theInstance.getClass() == TheTargetClass.class

As to testing whether a class is a "full" class, just negate all the test you mentioned. This first test is already an efficient filter... And do not forget .isSynthetic().

like image 23
fge Avatar answered Sep 28 '22 16:09

fge