Класс isAssignableFrom () метод в Java с примерами
Метод isAssignableFrom () класса java.lang.Class используется для проверки совместимости объекта указанного класса для назначения экземпляру этого класса. Он будет совместим, если оба класса одинаковы или указанный класс является суперклассом или суперинтерфейсом. Метод возвращает true, если объект указанного класса может быть приведен к экземпляру этого класса. В противном случае возвращается false.
Параметр: Этот метод принимает класс в качестве параметра, который является указанным классом, чей объект проверяется на совместимость с этим экземпляром класса.
Ниже программы демонстрируют метод isAssignableFrom ().
// Java-программа для демонстрации метода isAssignableFrom ()
public static void main(String[] args)
// возвращает объект Class для этого класса
Class myClass = Class.forName( «Test» );
System.out.println( «Class represented by myClass: «
// получить экземпляр класса, используя метод forName ()
Class c = Class.forName( «java.lang.String» );
System.out.println( «Class represented by c: «
// Проверка совместимости объекта c
// используя метод isAssignableFrom ()
System.out.println( «Is c compatible: «
// Java-программа для демонстрации метода isAssignableFrom ()
public static void main(String[] args)
// возвращает объект Class для этого класса
Class myClass = Class.forName( «Test» );
System.out.println( «Class represented by myClass: «
// получить экземпляр класса, используя метод forName ()
Type. Is Assignable From(Type) Метод
Определение
Некоторые сведения относятся к предварительной версии продукта, в которую до выпуска могут быть внесены существенные изменения. Майкрософт не предоставляет никаких гарантий, явных или подразумеваемых, относительно приведенных здесь сведений.
Определяет, можно ли присвоить экземпляр указанного типа c переменной текущего типа.
Параметры
Тип для сравнения с текущим типом.
Возвращаемое значение
c и текущий экземпляр принадлежат к одному типу.
c прямо или косвенно унаследован от текущего экземпляра. Параметр c является производным непосредственно от текущего экземпляра, если он наследуется от него. Параметр c является косвенно производным от текущего экземпляра, если он наследуется от последовательности одного или нескольких классов, наследуемых от текущего экземпляра.
c представляет тип значения, а текущий экземпляр представляет значение null ( значение null (Of c) в Visual Basic).
Реализации
Примеры
В следующем примере демонстрируется IsAssignableFrom метод с использованием определенных классов, целочисленных массивов и универсальных типов.
Комментарии
Таким образом, этот метод гарантирует, что строка кода, подобная приведенной ниже, будет выполняться во время выполнения без возникновения InvalidCastException исключения или аналогичного исключения:
Этот метод может быть переопределен производным классом.
В чем разница между экземпляром и классом.isAssignableFrom(. )?
что из следующего лучше?
единственное различие, о котором я знаю, когда » a » равно null, первый возвращает false, а второй создает исключение. Кроме этого, они всегда дают один и тот же результат?
13 ответов
instanceof можно использовать только со ссылочными типами, а не примитивными типами. isAssignableFrom() может использоваться с любыми объектами класса:
говорим с точки зрения производительности :
TL; DR
использовать isInstance или instanceof, которые имеют аналогичные характеристики. isAssignableFrom немного медленнее.
сортировка по производительности:
на основе эталона 2000 итераций на JAVA 8 Windows x64, с 20 итерациями прогрева.
в теории
используя мягкое как Просмотр кода мы можем перевести каждый оператор в байт-код.
измеряя, сколько инструкций байт-кода используется каждым оператором, мы могли бы ожидать instanceof и isInstance будет быстрее, чем isAssignableFrom. Однако фактическая производительность не определяется байт-кодом, но машинным кодом (который зависит от платформы). Давайте сделаем микро-тест для каждого из операторов.
эталон
кредит: как посоветовал @aleksandr-dubinsky, и спасибо @yura за предоставление базового кода, вот JMH benchmark (см. Это руководство по настройке):
дал следующие результаты (балл ряд операций за один раз юнит, поэтому, чем выше оценка, тем лучше):
предупреждение
чтобы дать вам пример, возьмите следующий цикл:
благодаря JIT код оптимизирован в какой-то момент, и мы получаем:
Примечание
Первоначально этот пост делал свой собственный бенчмарк с использованием на цикл в raw JAVA, который дал ненадежные результаты, поскольку некоторая оптимизация, как раз вовремя, может устранить цикл. Таким образом, он в основном измерял, сколько времени занимает компилятор JIT для оптимизации цикла: см. тест производительности не зависит от количества итераций дополнительные детали
Isassignablefrom java для чего
Class has no public constructor. Instead Class objects are constructed automatically by the Java Virtual Machine as classes are loaded and by calls to the defineClass method in the class loader.
The following example uses a Class object to print the class name of an object:
System.out.println(«The name of class Foo is: «+Foo.class.getName());
Method Summary
| Modifier and Type | Method and Description |
|---|---|
| Class | asSubclass(Class clazz) |
Methods inherited from class java.lang.Object
Method Detail
toString
forName
Class.forName(className, true, currentLoader)
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 an array class, the component type of the array class is loaded but not initialized.
For example, in an instance method the expression:
Class.forName(«Foo», true, this.getClass().getClassLoader())
newInstance
isInstance
isAssignableFrom
isInterface
isArray
isPrimitive
isAnnotation
isSynthetic
getName
If this class object represents a primitive type or void, then the name returned is a String equal to the Java language keyword corresponding to the primitive type or void.
If this class object represents a class of arrays, then the internal form of the name consists of the name of the element type preceded by one or more ‘ [ ‘ characters representing the depth of the array nesting. The encoding of element type names is as follows:
Element Type Encoding boolean Z byte B char C class or interface Lclassname; double D float F int I long J short S
The class or interface name classname is the binary name of the class specified above.
getClassLoader
If a security manager is present, and the caller’s class loader is not null and the caller’s class loader is not the same as or an ancestor of the class loader for the class whose class loader is requested, then this method calls the security manager’s checkPermission method with a RuntimePermission(«getClassLoader») permission to ensure it’s ok to access the class loader for the class.
If this object represents a primitive type or void, null is returned.
getTypeParameters
getSuperclass
getGenericSuperclass
If the superclass is a parameterized type, the Type object returned must accurately reflect the actual type parameters 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 represents either the Object class, an interface, a primitive type, or void, then null is returned. If this object represents an array class then the Class object representing the Object class is returned.
getPackage
Packages have attributes for versions and specifications only if the information was defined in the manifests that accompany the classes, and if the class loader created the package instance with the attributes from the manifest.
getInterfaces
If this object represents a class, the return value is an array containing objects representing all interfaces 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 object. For example, given the declaration:
class Shimmer implements FloorWax, DessertTopping
If this object represents an interface, the array contains objects representing all interfaces 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 object.
If this object represents a class or interface that implements no interfaces, the method returns an array of length 0.
If this object represents a primitive type or void, the method returns an array of length 0.
getGenericInterfaces
If a superinterface is a parameterized type, the Type object returned for it must accurately reflect the actual type parameters 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 object represents a class, the return value is an array containing objects representing all interfaces 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 object. In the case of an array class, the interfaces Cloneable and Serializable are returned in that order.
If this 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 object.
If this object represents a class or interface that implements no interfaces, the method returns an array of length 0.
If this object represents a primitive type or void, the method returns an array of length 0.
getComponentType
getModifiers
The modifier encodings are defined in The Java Virtual Machine Specification, table 4.1.
getSigners
getEnclosingMethod
getEnclosingConstructor
getDeclaringClass
getEnclosingClass
getSimpleName
The simple name of an array is the simple name of the component type with «[]» appended. In particular the simple name of an array whose component type is anonymous is «[]».
getCanonicalName
isAnonymousClass
isLocalClass
isMemberClass
getClasses
getFields
Specifically, if this Class object represents a class, this method returns the public fields of this class and of all its superclasses. If this Class object represents an interface, this method returns the fields of this interface and of all its superinterfaces.
The implicit length field for array class is not reflected by this method. User code should use the methods of class Array to manipulate arrays.
See The Java Language Specification, sections 8.2 and 8.3.
getMethods
The class initialization method is not included in the returned array. If the class declares multiple public member methods with the same parameter types, they are all included in the returned array.
See The Java Language Specification, sections 8.2 and 8.4.
getConstructors
getField
See The Java Language Specification, sections 8.2 and 8.3.
getMethod
Note that there may be more than one matching method in a class because while the Java language forbids a class to declare multiple methods with the same signature but different return types, the Java virtual machine does not. This increased flexibility in the virtual machine can be used to implement various language features. For example, covariant returns can be implemented with bridge methods; the bridge method and the method being overridden would have the same signature but different return types.
See The Java Language Specification, sections 8.2 and 8.4.
getConstructor
getDeclaredClasses
getDeclaredFields
See The Java Language Specification, sections 8.2 and 8.3.
getDeclaredMethods
See The Java Language Specification, section 8.2.
getDeclaredConstructors
See The Java Language Specification, section 8.2.
getDeclaredField
getDeclaredMethod
getDeclaredConstructor
getResourceAsStream
Where the modified_package_name is the package name of this object with ‘/’ substituted for ‘.’ ('\u002e').
getResource
Where the modified_package_name is the package name of this object with ‘/’ substituted for ‘.’ ('\u002e').
getProtectionDomain
desiredAssertionStatus
Few programmers will have any need for this method; it is provided for the benefit of the JRE itself. (It allows a class to determine at the time that it is initialized whether assertions should be enabled.) Note that this method is not guaranteed to return the actual assertion status that was (or will be) associated with the specified class when it was (or will be) initialized.
isEnum
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
isAnnotationPresent
getAnnotations
getDeclaredAnnotations
Submit a bug or feature
For further API reference and developer documentation, see Java SE Documentation. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.
Copyright © 1993, 2020, Oracle and/or its affiliates. All rights reserved. Use is subject to license terms. Also see the documentation redistribution policy.
Вещи, которые вы [возможно] не знали о Java
Эта статья разбавит мой поток сознания о производительности. Поговорим о забавных вещах в яве и околояве, о которых вы возможно не знали. О некоторых из перечисленных я сам узнал недавно, так что считаю, что большинство читателей найдёт для себя хотя бы пару-тройку любопытных моментов.
assert может принимать 2 аргумента
Обычно assert используется для проверки некоторого условия и бросает AssertionError если условие не удовлетворяется. Чаще всего проверка выглядит так:
Однако, она может быть и такой:
За без малого 6 с половиной лет работы с явой расширенное использование ключевого слова assert я видел лишь однажды.
strictfp
Это не ругательство — это малоизвестное ключевое слово. Если верить документации, его использование включает строгую арифметику для чисел с плавающей запятой:
можно лёгким движением руки превратить в
Также это ключевое слово может применятся к отдельным методам:
Подробнее о его использовании можно прочитать в вики-статье. Вкратце: когда-то это ключевое слово было добавлено для обеспечения переносимости, т.к. точность обработки чисел с плавающей запятой на разных процессорах могла быть разной.
continue может принимать аргумент
Узнал об этом на прошлой неделе. Обычно мы пишем так:
Подобное использование неявно предполагает возвращение в начало цикла и следующий проход. Иными словами, код выше можно переписать как:
Однако, вернуться из цикла можно и во внешний цикл, если таковой имеется:
Обратите внимание, счётчик i при возвращении в точку outer не сбрасывается, так что цикл является конечным.
При вызове vararg-метода без аргументов всё равно создаётся пустой массив
Когда мы смотрим на вызов такого метода извне, то кажется, что беспокоится не о чем:
Мы ведь ничего не передали в метод, не так ли? А вот если посмотреть изнутри, то всё не так радужно:
Опыт подтверждает опасения:
Избавится от ненужного массива при отсутствии аргументов можно передавая null :
Сборщику мусора действительно полегчает:
Код с null выглядит очень некрасиво, компилятор (и «Идея») будет ругаться, так что используйте этот подход в действительно горячем коде и снабдив его комментарием.
Выражение switch-case не поддерживает java.lang.Class
Этот код просто не компилируется:
Тонкости присваивания и Class.isAssignableFrom()
А теперь подумайте, какое значение вернёт этот метод:
Мораль: когда кажется — креститься надо надо перечитывать документацию.
Из этого примера проистекает ещё один неочевидный факт:
Открыв исходники java.lang.Integer увидим там вот это:
Глядя на вызов Class.getPrimitiveClass(«int») может возникнуть соблазн выпилить его и заменить на:
Самое удивительное, что JDK с подобными изменениями (для всех примитивов) соберётся, а виртуальная машина запустится. Правда проработает она недолго:
Ошибка вылезает вот здесь :
С упомянутыми изменениями byte.class возвращает null и ломает ансейф.
Spring Data JPA позволяет объявить частично работоспособный репозиторий
Завершу статью курьёзной ошибкой, возникшей на стыке Спринг Даты и Хибернейта. Вспомним, как мы объявляем репозиторий, обслуживающий некую сущность:
Опытные пользователи знают, что при поднятии контекста Спринг Дата проверяет все репозитории и сразу валит всё приложение при попытке описать, к примеру, кривой запрос:
Однако, ничто не мешает нам объявить репозиторий с левым типом ключа:
Этот репозиторий не только поднимется, но и будет частично работоспособен, например, метод findAll() отработает «на ура». А вот методы, использующие ключ ожидаемо упадут с ошибкой:
Всё дело в том, что Спринг Дата не сравнивает классы ключа сущности и ключа привязанного к ней репозитория. Происходит это не от хорошей жизни, а из-за неспособности Хибернейта выдать правильный тип ключа в определённых случаях: https://hibernate.atlassian.net/browse/HHH-10690
На этом всё, надеюсь, мой обзор был вам полезен и интересен.
Поздравляю вас с наступившим Новым годом и желаю копать яву глубже и шире!



