5

java.lang.Class 具有测试给定类型是否为的方法:

  • is注解
  • 是数组
  • isEnum
  • 是接口
  • 是原始的

但是如何测试 Class ( instanceof Classis true) 类型的对象表示已声明的非抽象类,而不是在接口、枚举、基元、数组等中。例如:

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().
      }
}

我一直在寻找 isClass 方法,但没有。


更新

我看到我的问题引起的混乱——而有些人得到了我的问题。

我做了一些进一步的研究,发现在 .NET

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

这是一个 isClass 成员,我在 java.lang.Class 中寻找类似的方法。

我现在知道,Java 中的等价物是测试所有其他 isXXX 方法以发现它不是一个类。

4

5 回答 5

6

你的问题似乎有脱节。一切都是一个类(除了原语——该isPrimitive()方法实际上意味着该类是一个自动装箱类型)。

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

那将是多余的。你已经知道这是一个类。因为你有一个Class.

出于某种原因,您似乎想知道它不是您列出的方法告诉您的任何类类型,在这种情况下,您只需进行检查以否定这些选项:

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

    // Not any of those things.

}
于 2013-06-19T17:46:18.287 回答
4

Class对象是单例。因此,如果您有任何类型的实例,您可以使用以下方法测试它是否是一个确切的类实例:

theInstance.getClass() == TheTargetClass.class

至于测试一个类是否是“完整”类,只需否定你提到的所有测试。这第一个测试已经是一个有效的过滤器......而且不要忘记.isSynthetic()

于 2013-06-19T17:36:42.223 回答
3

Not so readable but

object.getClass().getModifiers() < 30 //abstract classes are not included

or in a more readable way:

object.getClass().getModifiers() < Modifier.PROTECTED + Modifier.STATIC + Modifier.FINAL

seems to work, being more neat (but more obscure) than

!(!isInterface() && !isEnum() && !is ...) 

A simple class can only have these modifiers:

public static final int PUBLIC           = 0x00000001;
public static final int PRIVATE          = 0x00000002;
public static final int PROTECTED        = 0x00000004;
public static final int STATIC           = 0x00000008;
public static final int FINAL            = 0x00000010;

while abstract, interafce, enum or annotation has larger values (over 200).

You can see the Modifiers of a class by calling Modifier.toString(myClass.getModifiers()). The getModifiers() class returns the sum in hexa of all modifiers (as I have tested on some values; the implementation is native).

于 2013-06-19T18:03:06.293 回答
2

A partial solution: You can try to execute the Class's newInstance method. If the class is abstract or an interface an InstantiationException will be thrown- Otherwise, you're good.

The problem is that creating a new instance in a class you don't know might have unknown effects, or the class might not have a default constructor.

于 2013-06-19T17:53:30.023 回答
0

两个适合您的选项:

  1. 你可以做class instanceof Object
  2. 您可以检查所有其他is...()方法。如果它们都是假的,那么你就有了一门课。
于 2013-06-19T17:37:25.377 回答