Как получить имя класса java
Перейти к содержимому

Как получить имя класса java

  • автор:

Русские Блоги

Возвращает имя класса представление класса в виртуальной машине.

  • getCanonicalName()

Возвращает, скорее всего, чтобы понять имена классов.

  • getSimpleName()

Возвращает аббревиатуру класса.

В чем разница?

К примеру, они смотрят на их основные различия.

Программа выводит следующие результаты.

[Lcom.test.TestClass$TestInnerClass; Стоит explanating.

Это кодирование возвратов и параметров функции называется Javanative Интерфейс FieldDescriptors.

[ Представляет массивы, один представляет собой одномерный массив, например, [[ Представляет собой двумерный массив. Потом L Представление класса дескриптора, окончательный ; Обозначает конец имени класса.

в заключение

1. Из приведенных выше результатов, можно видеть, что GetName () и getcanonicalname () не отличается при получении нормального имени класса, который отличается от класса и класса массива внутреннего.

2, getSimpleName () ничем не отличается от обычного класса и имен внутренних классов, есть разница между получением класса массива.

Сканирование фокусировки на нашем общественном аккаунте WECHAT, не обновляйте каждый день.

Определить имя класса в Java

В этом посте будет обсуждаться, как определить имя класса базового класса объектов в Java.

1. Класс get*Name() методы

Самый простой способ — вызвать getClass() метод, возвращающий имя класса или интерфейс, представленный объектом, не являющимся массивом. Мы также можем использовать getSimpleName() или же getCanonicalName() , который возвращает простое имя (как в исходном коде) и каноническое имя базового класса соответственно. getTypeName() является недавним дополнением к JDK в Java SE 8, которое внутренне вызывает getClass() .

Получение имени класса в Java

В этом руководстве мы узнаем о четырех способах получения имени класса из методов APIClass:getSimpleName(), getName(), getTypeName() иgetCanonicalName(). .

Эти методы могут сбивать с толку из-за их похожих имен и их несколько расплывчатых Javadocs. Они также имеют некоторые нюансы, когда речь идет о примитивных типах, типах объектов, внутренних или анонимных классах и массивах.

2. Получение простого имени

Начнем с методаgetSimpleName().

В Java есть два типа имен:simple иqualified. A simple name consists of a unique identifier while a qualified name is a sequence of simple names separated by dots.

Как следует из названия,getSimpleName() возвращает простое имя базового класса, то естьthe name it has been given in the source code.

Представим себе следующий класс:

Его простое имя будетRetrieveClassName:

Мы также можем получить примитивные типы и массивы простых имен. Для примитивных типов это будут просто их имена, напримерint, boolean илиfloat.

А для массивов метод вернетthe simple name of the type of the array followed by a pair opening and closing brackets for each dimension of the array ([]):

Следовательно, для двумерного массиваString вызовgetSimpleName() для его класса вернетString[][].

Наконец, есть особый случай анонимных классов. Calling getSimpleName() on an anonymous class will return an empty string.с

3. Получение других имен

Теперь пора посмотреть, как мы получим имя класса, имя типа или каноническое имя. В отличие отgetSimpleName(), эти имена призваны дать больше информации о классе.

МетодgetCanonicalName() всегда возвращает каноническое имяas defined in the Java Language Specification.

Что касается других методов, вывод может немного отличаться в зависимости от вариантов использования. Мы увидим, что это означает для различных типов примитивов и объектов.

3.1. Примитивные типы

Начнем с примитивных типов, они простые. For primitive types, all three methods getName(), getTypeName() and getCanonicalName() will return the same result as getSimpleName():

3.2. Типы объектов

Теперь посмотрим, как эти методы работают с типами объектов. Их поведение в целом одинаково:they all return the canonical name of the class.

В большинстве случаев это квалифицированное имя, которое содержит простые имена всех пакетов классов, а также простое имя класса:

3.3. Внутренние классы

В предыдущем разделе мы видели общее поведение этих вызовов методов, но есть несколько исключений.

Внутренние классы являются одним из них. МетодыgetName() andgetTypeName() ведут себя иначе, чем методgetCanonicalName() для внутренних классов.

getCanonicalName() still returns the canonical name of the class, то есть каноническое имя включающего класса плюс простое имя внутреннего класса, разделенное точкой.

С другой стороны, методыgetName() andgetTypeName() возвращают почти то же самое, ноuse a dollar as the separator between the enclosing class canonical name and the inner class simple name.

Представим себе внутренний классInnerClass нашегоRetrieveClassName:

Тогда каждый вызов обозначает внутренний класс немного по-другому:

3.4. Анонимные классы

Анонимные классы являются еще одним исключением.

Как мы уже видели, у них нет простого имени, а естьthey also don’t have a canonical name. Следовательно,getCanonicalName() ничего не возвращает. In opposition to getSimpleName(), getCanonicalName() will return null, а не пустая строка при вызове анонимного класса.

Что касаетсяgetName() иgetTypeName(), они вернутcalling class canonical name followed by a dollar and a number representing the position of the anonymous class among all anonymous classes created in the calling class.

Проиллюстрируем это на примере. Мы создадим здесь два анонимных класса и вызовемgetName() для первого иgetTypeName() для второго, объявив их вcom.example.Main:

Следует отметить, что второй вызов возвращает имя с увеличенным числом в конце, как это применяется ко второму анонимному классу.

3.5. Массивы

Наконец, давайте посмотрим, как массивы обрабатываются тремя вышеуказанными методами.

Чтобы указать, что мы имеем дело с массивами, каждый метод обновит свой стандартный результат. The getTypeName() and getCanonicalName() methods will append pairs of brackets to their result.с

Давайте посмотрим на следующий пример, в котором мы вызываемgetTypeName() andgetCanonicalName() для двумерного массиваInnerClass:

Обратите внимание, что в первом вызове вместо точки используется знак доллара, а не внутренняя часть класса.

Теперь посмотрим, как работает методgetName(). При вызове для массива примитивных типов он вернетan opening bracket and a letter representing the primitive type. . Давайте проверим это в следующем примере, вызвав этот метод для двумерного массива примитивных целых чисел:

С другой стороны, при вызове массива объектов он будетadd an opening bracket and the L letter to its standard result and finish with a semi-colon. Давайте попробуем это на массивеRetrieveClassName:

4. Заключение

В этой статье мы рассмотрели четыре метода доступа к имени класса в Java. Это следующие методы:getSimpleName(), getName(), getTypeName() иgetCanonicalName().

Мы узнали, что первый просто возвращает имя исходного кода класса, в то время как другие предоставляют больше информации, такой как имя пакета и указание, является ли класс внутренним или анонимным классом.

Class Class<T>

The methods of class Class expose many characteristics of a class or interface. Most characteristics are derived from the class file that the class loader passed to the Java Virtual Machine or from the class file passed to Lookup::defineClass or Lookup::defineHiddenClass . A few characteristics are determined by the class loading environment at run time, such as the module returned by getModule() .

The following example uses a Class object to print the class name of an object:

Some methods of class Class expose whether the declaration of a class or interface in Java source code was enclosed within another declaration. Other methods describe how a class or interface is situated in a nest. A nest is a set of classes and interfaces, in the same run-time package, that allow mutual access to their private members. The classes and interfaces are known as nestmates. One nestmate acts as the nest host, and enumerates the other nestmates which belong to the nest; each of them in turn records it as the nest host. The classes and interfaces which belong to a nest, including its host, are determined when class files are generated, for example, a Java compiler will typically record a top-level class as the host of a nest where the other members are the classes and interfaces whose declarations are enclosed within the top-level class declaration.

  • A hidden class or interface cannot be referenced by the constant pools of other classes and interfaces.
  • A hidden class or interface cannot be described in nominal form by Class::describeConstable , ClassDesc::of , or ClassDesc::ofDescriptor .
  • A hidden class or interface cannot be discovered by Class::forName or ClassLoader::loadClass .

Nested Class Summary

Nested classes/interfaces declared in interface java.lang.invoke.TypeDescriptor

Method Summary

Methods declared in class java.lang.Object

Method Details

toString

toGenericString

Note that since information about the runtime representation of a type is being generated, modifiers not present on the originating source code or illegal on the originating source code may be present.

forName

For example, the following code fragment returns the runtime Class descriptor for the class named java.lang.Thread :

A call to forName(«X») causes the class named X to be initialized.

forName

If name denotes a primitive type or void, an attempt will be made to locate a user-defined class in the unnamed package whose name is name . Therefore, this method cannot be used to obtain any of the Class objects representing primitive types or void.

If name denotes an array class, the component type of the array class is loaded but not initialized.

For example, in an instance method the expression:

forName

This method attempts to locate and load the class or interface. It does not link the class, and does not run the class initializer. If the class is not found, this method returns null .

If the class loader of the given module defines other modules and the given name is a class defined in a different module, this method returns null after the class is loaded.

This method does not check whether the requested class is accessible to its caller.

  • if the caller is not the specified module and RuntimePermission(«getClassLoader») permission is denied; or
  • access to the module content is denied. For example, permission check will be performed when a class loader calls ModuleReader.open(String) to read the bytes of a class file in a module.

newInstance

The call can be replaced by The latter sequence of calls is inferred to be able to throw the additional exception types InvocationTargetException and NoSuchMethodException . Both of these exception types are subclasses of ReflectiveOperationException .

isInstance

Specifically, if this Class object represents a declared class, this method returns true if the specified Object argument is an instance of the represented class (or of any of its subclasses); it returns false otherwise. If this Class object represents an array class, this method returns true if the specified Object argument can be converted to an object of the array class by an identity conversion or by a widening reference conversion; it returns false otherwise. If this Class object represents an interface, this method returns true if the class or any superclass of the specified Object argument implements this interface; it returns false otherwise. If this Class object represents a primitive type, this method returns false .

isAssignableFrom

Specifically, this method tests whether the type represented by the specified Class parameter can be converted to the type represented by this Class object via an identity conversion or via a widening reference conversion. See The Java Language Specification , sections 5.1.1 and 5.1.4, for details.

isInterface

isArray

isPrimitive

There are nine predefined Class objects to represent the eight primitive types and void. These are created by the Java Virtual Machine, and have the same names as the primitive types that they represent, namely boolean , byte , char , short , int , long , float , and double .

These objects may only be accessed via the following public static final variables, and are the only Class objects for which this method returns true .

isAnnotation

isSynthetic

getName

  • If the class or interface is not hidden, then the binary name of the class or interface is returned.
  • If the class or interface is hidden, then the result is a string of the form: N + ‘/’ + <suffix> where N is the binary name indicated by the class file passed to Lookup::defineHiddenClass , and <suffix> is an unqualified name.

If this Class object represents an array class, then the result is a string consisting of one or more ‘ [ ‘ characters representing the depth of the array nesting, followed by the element type as encoded using the following table:

Element types and encodings

Element Type Encoding
boolean Z
byte B
char C
class or interface with binary name N L N ;
double D
float F
int I
long J
short S

If this Class object represents a primitive type or void , then the result is a string with the same spelling as the Java language keyword which corresponds to the primitive type or void .

getClassLoader

If this Class object represents a primitive type or void, null is returned.

getModule

getTypeParameters

getSuperclass

getGenericSuperclass

If the superclass is a parameterized type, the Type object returned must accurately reflect the actual type arguments used in the source code. The parameterized type representing the superclass is created if it had not been created before. See the declaration of ParameterizedType for the semantics of the creation process for parameterized types. If this Class object represents either the Object class, an interface, a primitive type, or void, then null is returned. If this Class object represents an array class then the Class object representing the Object class is returned.

getPackage

If this class represents an array type, a primitive type or void, this method returns null .

getPackageName

If this class is a top level class, then this method returns the fully qualified name of the package that the class is a member of, or the empty string if the class is in an unnamed package.

If this class is a member class, then this method is equivalent to invoking getPackageName() on the enclosing class.

If this class is a local class or an anonymous class, then this method is equivalent to invoking getPackageName() on the declaring class of the enclosing method or enclosing constructor.

If this class represents an array type then this method returns the package name of the element type. If this class represents a primitive type or void then the package name » java.lang » is returned.

getInterfaces

If this Class object represents a class, the return value is an array containing objects representing all interfaces directly implemented by the class. The order of the interface objects in the array corresponds to the order of the interface names in the implements clause of the declaration of the class represented by this Class object. For example, given the declaration:

If this Class object represents an interface, the array contains objects representing all interfaces directly extended by the interface. The order of the interface objects in the array corresponds to the order of the interface names in the extends clause of the declaration of the interface represented by this Class object.

If this Class object represents a class or interface that implements no interfaces, the method returns an array of length 0.

If this Class object represents a primitive type or void, the method returns an array of length 0.

If this Class object represents an array type, the interfaces Cloneable and java.io.Serializable are returned in that order.

getGenericInterfaces

If a superinterface is a parameterized type, the Type object returned for it must accurately reflect the actual type arguments used in the source code. The parameterized type representing each superinterface is created if it had not been created before. See the declaration of ParameterizedType for the semantics of the creation process for parameterized types.

If this Class object represents a class, the return value is an array containing objects representing all interfaces directly implemented by the class. The order of the interface objects in the array corresponds to the order of the interface names in the implements clause of the declaration of the class represented by this Class object.

If this Class object represents an interface, the array contains objects representing all interfaces directly extended by the interface. The order of the interface objects in the array corresponds to the order of the interface names in the extends clause of the declaration of the interface represented by this Class object.

If this Class object represents a class or interface that implements no interfaces, the method returns an array of length 0.

If this Class object represents a primitive type or void, the method returns an array of length 0.

If this Class object represents an array type, the interfaces Cloneable and java.io.Serializable are returned in that order.

getComponentType

getModifiers

If the underlying class is an array class, then its public , private and protected modifiers are the same as those of its component type. If this Class object represents a primitive type or void, its public modifier is always true , and its protected and private modifiers are always false . If this Class object represents an array class, a primitive type or void, then its final modifier is always true and its interface modifier is always false . The values of its other modifiers are not determined by this specification.

The modifier encodings are defined in section 4.1 of The Java Virtual Machine Specification .

getSigners

getEnclosingMethod

  • the caller’s class loader is not the same as the class loader of the enclosing class and invocation of s.checkPermission method with RuntimePermission(«accessDeclaredMembers») denies access to the methods within the enclosing class
  • the caller’s class loader is not the same as or an ancestor of the class loader for the enclosing class and invocation of s.checkPackageAccess() denies access to the package of the enclosing class

getEnclosingConstructor

  • the caller’s class loader is not the same as the class loader of the enclosing class and invocation of s.checkPermission method with RuntimePermission(«accessDeclaredMembers») denies access to the constructors within the enclosing class
  • the caller’s class loader is not the same as or an ancestor of the class loader for the enclosing class and invocation of s.checkPackageAccess() denies access to the package of the enclosing class

getDeclaringClass

getEnclosingClass

getSimpleName

The simple name of an array class is the simple name of the component type with «[]» appended. In particular the simple name of an array class whose component type is anonymous is «[]».

getTypeName

getCanonicalName

  • a local class
  • a anonymous class
  • a hidden class
  • an array whose component type does not have a canonical name

isAnonymousClass

isLocalClass

isMemberClass

getClasses

getFields

If this Class object represents a class or interface with no accessible public fields, then this method returns an array of length 0.

If this Class object represents a class, then this method returns the public fields of the class and of all its superclasses and superinterfaces.

If this Class object represents an interface, then this method returns the fields of the interface and of all its superinterfaces.

If this Class object represents an array type, a primitive type, or void, then this method returns an array of length 0.

The elements in the returned array are not sorted and are not in any particular order.

getMethods

If this Class object represents an array type, then the returned array has a Method object for each of the public methods inherited by the array type from Object . It does not contain a Method object for clone() .

If this Class object represents an interface then the returned array does not contain any implicitly declared methods from Object . Therefore, if no methods are explicitly declared in this interface or any of its superinterfaces then the returned array has length 0. (Note that a Class object which represents a class always has public methods, inherited from Object .)

The returned array never contains methods with names » <init> » or » <clinit> «.

The elements in the returned array are not sorted and are not in any particular order.

  1. A union of methods is composed of:
    1. C’s declared public instance and static methods as returned by getDeclaredMethods() and filtered to include only public methods.
    2. If C is a class other than Object , then include the result of invoking this algorithm recursively on the superclass of C.
    3. Include the results of invoking this algorithm recursively on all direct superinterfaces of C, but include only instance methods.
    1. N is declared by a class and M is declared by an interface; or
    2. N and M are both declared by classes or both by interfaces and N’s declaring type is the same as or a subtype of M’s declaring type (clearly, if M’s and N’s declaring types are the same type, then M and N are the same method).

    getConstructors

    getField

    1. If C declares a public field with the name specified, that is the field to be reflected.
    2. If no field was found in step 1 above, this algorithm is applied recursively to each direct superinterface of C. The direct superinterfaces are searched in the order they were declared.
    3. If no field was found in steps 1 and 2 above, and C has a superclass S, then this algorithm is invoked recursively upon S. If C has no superclass, then a NoSuchFieldException is thrown.

    If this Class object represents an array type, then this method does not find the length field of the array type.

    getMethod

    If this Class object represents an array type, then this method finds any public method inherited by the array type from Object except method clone() .

    If this Class object represents an interface then this method does not find any implicitly declared method from Object . Therefore, if no methods are explicitly declared in this interface or any of its superinterfaces, then this method does not find any method.

    This method does not find any method with name » <init> » or » <clinit> «.

    1. A union of methods is composed of:
      1. C’s declared public instance and static methods as returned by getDeclaredMethods() and filtered to include only public methods that match given name and parameterTypes
      2. If C is a class other than Object , then include the result of invoking this algorithm recursively on the superclass of C.
      3. Include the results of invoking this algorithm recursively on all direct superinterfaces of C, but include only instance methods.
      1. N is declared by a class and M is declared by an interface; or
      2. N and M are both declared by classes or both by interfaces and N’s declaring type is the same as or a subtype of M’s declaring type (clearly, if M’s and N’s declaring types are the same type, then M and N are the same method).

      getConstructor

      The constructor to reflect is the public constructor of the class represented by this Class object whose formal parameter types match those specified by parameterTypes .

      getDeclaredClasses

      • the caller’s class loader is not the same as the class loader of this class and invocation of s.checkPermission method with RuntimePermission(«accessDeclaredMembers») denies access to the declared classes within this class
      • the caller’s class loader is not the same as or an ancestor of the class loader for the current class and invocation of s.checkPackageAccess() denies access to the package of this class

      getDeclaredFields

      If this Class object represents a class or interface with no declared fields, then this method returns an array of length 0.

      If this Class object represents an array type, a primitive type, or void, then this method returns an array of length 0.

      The elements in the returned array are not sorted and are not in any particular order.

      • the caller’s class loader is not the same as the class loader of this class and invocation of s.checkPermission method with RuntimePermission(«accessDeclaredMembers») denies access to the declared fields within this class
      • the caller’s class loader is not the same as or an ancestor of the class loader for the current class and invocation of s.checkPackageAccess() denies access to the package of this class

      getRecordComponents

      The components are returned in the same order that they are declared in the record header. The array is empty if this record class has no components. If the class is not a record class, that is isRecord() returns false , then this method returns null . Conversely, if isRecord() returns true , then this method returns a non-null value.

      The following method can be used to find the record canonical constructor:

      • the caller’s class loader is not the same as the class loader of this class and invocation of s.checkPermission method with RuntimePermission(«accessDeclaredMembers») denies access to the declared methods within this class
      • the caller’s class loader is not the same as or an ancestor of the class loader for the current class and invocation of s.checkPackageAccess() denies access to the package of this class

      getDeclaredMethods

      If this Class object represents a class or interface that has multiple declared methods with the same name and parameter types, but different return types, then the returned array has a Method object for each such method.

      If this Class object represents a class or interface that has a class initialization method <clinit> , then the returned array does not have a corresponding Method object.

      If this Class object represents a class or interface with no declared methods, then the returned array has length 0.

      If this Class object represents an array type, a primitive type, or void, then the returned array has length 0.

      The elements in the returned array are not sorted and are not in any particular order.

      • the caller’s class loader is not the same as the class loader of this class and invocation of s.checkPermission method with RuntimePermission(«accessDeclaredMembers») denies access to the declared methods within this class
      • the caller’s class loader is not the same as or an ancestor of the class loader for the current class and invocation of s.checkPackageAccess() denies access to the package of this class
      • Java programming language and JVM modeling in core reflection

      getDeclaredConstructors

      See The Java Language Specification , section 8.2.

      • the caller’s class loader is not the same as the class loader of this class and invocation of s.checkPermission method with RuntimePermission(«accessDeclaredMembers») denies access to the declared constructors within this class
      • the caller’s class loader is not the same as or an ancestor of the class loader for the current class and invocation of s.checkPackageAccess() denies access to the package of this class

      getDeclaredField

      If this Class object represents an array type, then this method does not find the length field of the array type.

      • the caller’s class loader is not the same as the class loader of this class and invocation of s.checkPermission method with RuntimePermission(«accessDeclaredMembers») denies access to the declared field
      • the caller’s class loader is not the same as or an ancestor of the class loader for the current class and invocation of s.checkPackageAccess() denies access to the package of this class

      getDeclaredMethod

      If this Class object represents an array type, then this method does not find the clone() method.

      • the caller’s class loader is not the same as the class loader of this class and invocation of s.checkPermission method with RuntimePermission(«accessDeclaredMembers») denies access to the declared method
      • the caller’s class loader is not the same as or an ancestor of the class loader for the current class and invocation of s.checkPackageAccess() denies access to the package of this class

      getDeclaredConstructor

      • the caller’s class loader is not the same as the class loader of this class and invocation of s.checkPermission method with RuntimePermission(«accessDeclaredMembers») denies access to the declared constructor
      • the caller’s class loader is not the same as or an ancestor of the class loader for the current class and invocation of s.checkPackageAccess() denies access to the package of this class

      getResourceAsStream

      If this class is in a named Module then this method will attempt to find the resource in the module. This is done by delegating to the module’s class loader findResource(String,String) method, invoking it with the module name and the absolute name of the resource. Resources in named modules are subject to the rules for encapsulation specified in the Module getResourceAsStream method and so this method returns null when the resource is a non-» .class » resource in a package that is not open to the caller’s module.

      Otherwise, if this class is not in a named module then the rules for searching resources associated with a given class are implemented by the defining class loader of the class. This method delegates to this Class object’s class loader. If this Class object was loaded by the bootstrap class loader, the method delegates to ClassLoader.getSystemResourceAsStream(java.lang.String) .

      • If the name begins with a ‘/’ ( ‘\u002f’ ), then the absolute name of the resource is the portion of the name following the ‘/’ .
      • Otherwise, the absolute name is of the following form:

      Where the modified_package_name is the package name of this object with ‘/’ substituted for ‘.’ ( ‘\u002e’ ).

      getResource

      If this class is in a named Module then this method will attempt to find the resource in the module. This is done by delegating to the module’s class loader findResource(String,String) method, invoking it with the module name and the absolute name of the resource. Resources in named modules are subject to the rules for encapsulation specified in the Module getResourceAsStream method and so this method returns null when the resource is a non-» .class » resource in a package that is not open to the caller’s module.

      Otherwise, if this class is not in a named module then the rules for searching resources associated with a given class are implemented by the defining class loader of the class. This method delegates to this Class object’s class loader. If this Class object was loaded by the bootstrap class loader, the method delegates to ClassLoader.getSystemResource(java.lang.String) .

      • If the name begins with a ‘/’ ( ‘\u002f’ ), then the absolute name of the resource is the portion of the name following the ‘/’ .
      • Otherwise, the absolute name is of the following form:

      Where the modified_package_name is the package name of this object with ‘/’ substituted for ‘.’ ( ‘\u002e’ ).

      getProtectionDomain

      desiredAssertionStatus

      isEnum

      isRecord

      The direct superclass of a record class is java.lang.Record . A record class is final. A record class has (possibly zero) record components; getRecordComponents() returns a non-null but possibly empty value for a record.

      Note that class Record is not a record class and thus invoking this method on class Record returns false .

      getEnumConstants

      asSubclass

      This method is useful when a client needs to «narrow» the type of a Class object to pass it to an API that restricts the Class objects that it is willing to accept. A cast would generate a compile-time warning, as the correctness of the cast could not be checked at runtime (because generic types are implemented by erasure).

      getAnnotation

      Note that any annotation returned by this method is a declaration annotation.

      isAnnotationPresent

      The truth value returned by this method is equivalent to: getAnnotation(annotationClass) != null

      getAnnotationsByType

      Note that any annotations returned by this method are declaration annotations.

      getAnnotations

      Note that any annotations returned by this method are declaration annotations.

      getDeclaredAnnotation

      Note that any annotation returned by this method is a declaration annotation.

      getDeclaredAnnotationsByType

      Note that any annotations returned by this method are declaration annotations.

      getDeclaredAnnotations

      Note that any annotations returned by this method are declaration annotations.

      getAnnotatedSuperclass

      If this Class object represents a class whose declaration does not explicitly indicate an annotated superclass, then the return value is an AnnotatedType object representing an element with no annotations.

      If this Class represents either the Object class, an interface type, an array type, a primitive type, or void, the return value is null .

      getAnnotatedInterfaces

      If this Class object represents a class, the return value is an array containing objects representing the uses of interface types to specify interfaces implemented by the class. The order of the objects in the array corresponds to the order of the interface types used in the ‘implements’ clause of the declaration of this Class object.

      If this Class object represents an interface, the return value is an array containing objects representing the uses of interface types to specify interfaces directly extended by the interface. The order of the objects in the array corresponds to the order of the interface types used in the ‘extends’ clause of the declaration of this Class object.

      If this Class object represents a class or interface whose declaration does not explicitly indicate any annotated superinterfaces, the return value is an array of length 0.

      If this Class object represents either the Object class, an array type, a primitive type, or void, the return value is an array of length 0.

      getNestHost

      If this Class object represents a primitive type, an array type, or void , then this method returns this , indicating that the represented entity belongs to the nest consisting only of itself, and is the nest host.

      isNestmateOf

      getNestMembers

      If this Class object represents a primitive type, an array type, or void , then this method returns a single-element array containing this .

      descriptorString

      • If the class or interface is not hidden, then the result is a field descriptor (JVMS 4.3.2) for the class or interface. Calling ClassDesc::ofDescriptor with the result descriptor string produces a ClassDesc describing this class or interface.
      • If the class or interface is hidden, then the result is a string of the form:

      • If the element type is not a hidden class or interface, then this array class can be described nominally. Calling ClassDesc::ofDescriptor with the result descriptor string produces a ClassDesc describing this array class.
      • If the element type is a hidden class or interface, then this array class cannot be described nominally. The result string is not a type descriptor.

      If this Class object represents a primitive type or void , then the result is a field descriptor string which is a one-letter code corresponding to a primitive type or void ( «B», «C», «D», «F», «I», «J», «S», «Z», «V» ) (JVMS 4.3.2).

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *