Java как определить класс объекта

Определение класса объекта в Java

Часто при работе с Java возникает ситуация, когда необходимо определить класс объекта. Возьмем для примера следующую ситуацию: имеется класс A , от которого наследуют классы B и C . Создается объект класса B или класса C , и требуется выяснить, к какому конкретно классу он принадлежит.

class A < >class B extends A < >class C extends A < >public class Test < public static void main(String[] args) < A obj = new B(); // Вопрос: какой класс у obj? >>

Для решения этой задачи в языке Java существуют несколько способов.

Оператор instanceof

Первый и самый простой способ — использовать оператор instanceof . Он возвращает true , если объект является экземпляром указанного класса или его подкласса, и false в противном случае.

if (obj instanceof B) < System.out.println("Объект является экземпляром класса B"); >else if (obj instanceof C) < System.out.println("Объект является экземпляром класса C"); >else

Метод getClass()

Второй способ — использовать метод getClass() . Он возвращает объект Class , который представляет класс данного объекта.

Class<?> clazz = obj.getClass(); System.out.println("Класс объекта: " + clazz.getName());

В данном случае будет выведено полное имя класса объекта.

Итог

Определение класса объекта в Java — распространенная задача, которую можно решить разными способами. Оператор instanceof и метод getClass() — лишь два из них. Выбор способа зависит от конкретной ситуации и требований к коду.

Читайте также:  Using dll in python

Источник

Retrieving Class Objects

The entry point for all reflection operations is java.lang.Class . With the exception of java.lang.reflect.ReflectPermission , none of the classes in java.lang.reflect have public constructors. To get to these classes, it is necessary to invoke appropriate methods on Class . There are several ways to get a Class depending on whether the code has access to an object, the name of class, a type, or an existing Class .

Object.getClass()

If an instance of an object is available, then the simplest way to get its Class is to invoke Object.getClass() . Of course, this only works for reference types which all inherit from Object . Some examples follow.

Class c = System.console().getClass();

There is a unique console associated with the virtual machine which is returned by the static method System.console() . The value returned by getClass() is the Class corresponding to java.io.Console .

enum E < A, B >Class c = A.getClass();

A is an instance of the enum E ; thus getClass() returns the Class corresponding to the enumeration type E .

byte[] bytes = new byte[1024]; Class c = bytes.getClass();

Since arrays are Objects , it is also possible to invoke getClass() on an instance of an array. The returned Class corresponds to an array with component type byte .

import java.util.HashSet; import java.util.Set; Set s = new HashSet(); Class c = s.getClass();

In this case, java.util.Set is an interface to an object of type java.util.HashSet . The value returned by getClass() is the class corresponding to java.util.HashSet .

The .class Syntax

If the type is available but there is no instance then it is possible to obtain a Class by appending «.class» to the name of the type. This is also the easiest way to obtain the Class for a primitive type.

boolean b; Class c = b.getClass(); // compile-time error Class c = boolean.class; // correct

Note that the statement boolean.getClass() would produce a compile-time error because a boolean is a primitive type and cannot be dereferenced. The .class syntax returns the Class corresponding to the type boolean .

Class c = java.io.PrintStream.class;

The variable c will be the Class corresponding to the type java.io.PrintStream .

The .class syntax may be used to retrieve a Class corresponding to a multi-dimensional array of a given type.

Class.forName()

If the fully-qualified name of a class is available, it is possible to get the corresponding Class using the static method Class.forName() . This cannot be used for primitive types. The syntax for names of array classes is described by Class.getName() . This syntax is applicable to references and primitive types.

Class c = Class.forName("com.duke.MyLocaleServiceProvider");

This statement will create a class from the given fully-qualified name.

Class cDoubleArray = Class.forName("[D"); Class cStringArray = Class.forName("[[Ljava.lang.String;");

The variable cDoubleArray will contain the Class corresponding to an array of primitive type double (that is, the same as double[].class ). The cStringArray variable will contain the Class corresponding to a two-dimensional array of String (that is, identical to String[][].class ).

TYPE Field for Primitive Type Wrappers

The .class syntax is a more convenient and the preferred way to obtain the Class for a primitive type; however there is another way to acquire the Class . Each of the primitive types and void has a wrapper class in java.lang that is used for boxing of primitive types to reference types. Each wrapper class contains a field named TYPE which is equal to the Class for the primitive type being wrapped.

There is a class java.lang.Double which is used to wrap the primitive type double whenever an Object is required. The value of Double.TYPE is identical to that of double.class .

Void.TYPE is identical to void.class .

Methods that Return Classes

There are several Reflection APIs which return classes but these may only be accessed if a Class has already been obtained either directly or indirectly.

Class.getSuperclass() Returns the super class for the given class.

Class c = javax.swing.JButton.class.getSuperclass();

The super class of javax.swing.JButton is javax.swing.AbstractButton . Class.getClasses() Returns all the public classes, interfaces, and enums that are members of the class including inherited members.

Class[] c = Character.class.getClasses();

Character contains two member classes Character.Subset and Character.UnicodeBlock . Class.getDeclaredClasses() Returns all of the classes interfaces, and enums that are explicitly declared in this class.

Class[] c = Character.class.getDeclaredClasses();
import java.lang.reflect.Field; Field f = System.class.getField("out"); Class c = f.getDeclaringClass();
public class MyClass < static Object o = new Object() < public void m() <>>; static Class = o.getClass().getEnclosingClass(); >

The declaring class of the anonymous class defined by o is null . Class.getEnclosingClass() Returns the immediately enclosing class of the class.

Class c = Thread.State.class().getEnclosingClass();
public class MyClass < static Object o = new Object() < public void m() <>>; static Class = o.getClass().getEnclosingClass(); >

Источник

Получить тип объекта в Java

Получить тип объекта в Java

  1. Получить тип объекта с помощью getClass() в Java
  2. Получить тип объекта с помощью instanceOf в Java
  3. Получить тип объекта класса, созданного вручную в Java

В этой статье мы узнаем, как получить тип объекта в Java. Если объект поступает из источника, полезно проверить тип объекта. Это место, где мы не можем проверить тип объектов, например из API или частного класса, к которому у нас нет доступа.

Получить тип объекта с помощью getClass() в Java

В первом методе мы проверяем тип Object классов-оболочек, таких как Integer и String . У нас есть два объекта, var1 и var2 , для проверки типа. Мы воспользуемся методом getClass() класса Object , родительского класса всех объектов в Java.

Проверяем класс по условию если . Поскольку классы-оболочки также содержат класс поля, возвращающий тип, мы можем проверить, чей тип совпадает с var1 и var2 . Ниже мы проверяем оба объекта трех типов.

public class ObjectType   public static void main(String[] args)   Object var1 = Integer.valueOf("15");  Object var2 = String.valueOf(var1);   if (var1.getClass() == Integer.class)   System.out.println("var1 is an Integer");  > else if (var1.getClass() == String.class)   System.out.println("var1 is a String");  > else if (var1.getClass() == Double.class)   System.out.println("var1 is a Double");  >   if (var2.getClass() == Integer.class)   System.out.println("var2 is an Integer");  > else if (var2.getClass() == String.class)   System.out.println("var2 is a String");  > else if (var2.getClass() == Double.class)   System.out.println("var2 is a Double");  >  > > 
var1 is an Integer var2 is a String 

Получить тип объекта с помощью instanceOf в Java

Другой способ получить тип объекта в Java — использовать функцию instanceOf ; он возвращается, если экземпляр объекта совпадает с заданным классом. В этом примере у нас есть объекты var1 и var2 , которые проверяются с этими тремя типами: Integer , String и Double ; если какое-либо из условий выполняется, мы можем выполнить другой код.

Поскольку var1 имеет тип Integer , условие var1 instanceOf Integer станет истинным, а var2 — Double , так что var2 instanceOf Double станет истинным.

public class ObjectType   public static void main(String[] args)   Object var1 = Integer.valueOf("15");  Object var2 = Double.valueOf("10");   if (var1 instanceof Integer)   System.out.println("var1 is an Integer");  > else if (var1 instanceof String)   System.out.println("var1 is a String");  > else if (var1 instanceof Double)   System.out.println("var1 is a Double");  >   if (var2 instanceof Integer)   System.out.println("var2 is an Integer");  > else if (var2 instanceof String)   System.out.println("var2 is a String");  > else if (var2 instanceof Double)   System.out.println("var2 is a Double");  >  > > 
var1 is an Integer var2 is a Double 

Получить тип объекта класса, созданного вручную в Java

Мы проверили типы классов-оболочек, но в этом примере мы получаем тип трех объектов трех созданных вручную классов. Мы создаем три класса: ObjectType2 , ObjectType3 и ObjectType4 .

ObjectType3 наследует ObjectType4, а ObjectType2 наследует ObjectType3. Теперь мы хотим узнать тип объектов всех этих классов. У нас есть три объекта: obj , obj2 и obj3 ; мы используем оба метода, которые мы обсуждали в приведенных выше примерах: getClass () и instanceOf.

Однако есть отличия между типом obj2 . Переменная obj2 вернула тип ObjectType4 , а ее класс — ObjectType3 . Это происходит потому, что мы наследуем класс ObjectType4 в ObjectType3 , а instanceOf проверяет все классы и подклассы. obj вернул ObjectType3 , потому что функция getClass() проверяет только прямой класс.

public class ObjectType   public static void main(String[] args)    Object obj = new ObjectType2();  Object obj2 = new ObjectType3();  Object obj3 = new ObjectType4();   if (obj.getClass() == ObjectType4.class)   System.out.println("obj is of type ObjectType4");  > else if (obj.getClass() == ObjectType3.class)   System.out.println("obj is of type ObjectType3");  > else if (obj.getClass() == ObjectType2.class)   System.out.println("obj is of type ObjectType2");  >   if (obj2 instanceof ObjectType4)   System.out.println("obj2 is an instance of ObjectType4");  > else if (obj2 instanceof ObjectType3)   System.out.println("obj2 is an instance of ObjectType3");  > else if (obj2 instanceof ObjectType2)   System.out.println("obj2 is an instance of ObjectType2");  >   if (obj3 instanceof ObjectType4)   System.out.println("obj3 is an instance of ObjectType4");  > else if (obj3 instanceof ObjectType3)   System.out.println("obj3 is an instance of ObjectType3");  > else if (obj3 instanceof ObjectType2)   System.out.println("obj3 is an instance of ObjectType2");  >   >  >  class ObjectType2 extends ObjectType3    int getAValue3()   System.out.println(getAValue2());  a = 300;  return a;  > >  class ObjectType3 extends ObjectType4    int getAValue2()   System.out.println(getAValue1());  a = 200;  return a;  >  >  class ObjectType4    int a = 50;   int getAValue1()   a = 100;  return a;  >  > 
obj is of type ObjectType2 obj2 is an instance of ObjectType4 obj3 is an instance of ObjectType4 

Rupam Saini is an android developer, who also works sometimes as a web developer., He likes to read books and write about various things.

Сопутствующая статья — Java Object

Источник

Оцените статью