Java получить тип данных

Как через рефлексию достать тип данных java

Чтобы получить тип данных переменной в Java , можно использовать рефлексию. Для этого нужно получить объект класса Class , представляющий тип данных переменной, и затем использовать его для получения нужной информации.

import java.lang.reflect.Field; public class ReflectionExample  public static void main(String[] args) throws NoSuchFieldException  MyClass obj = new MyClass(); Field field = obj.getClass().getDeclaredField("myField"); Class fieldType = field.getType(); System.out.println("Type of myField: " + fieldType.getName()); > > class MyClass  private String myField; > 
  • В этом примере мы создаем объект класса MyClass
  • Затем получаем объект Field для переменной myField с помощью метода getDeclaredField()
  • Затем мы вызываем метод getType() объекта Field , чтобы получить объект Class , представляющий тип данных переменной, и выводим его имя с помощью метода getName()

Источник

Получить тип объекта в 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

Источник

Java typeof Operator

Java typeof Operator

  1. Get the Type of a Variable/Value in Java
  2. Get the Type of Any Variable/Value in Java

This tutorial introduces how to get the data type of a variable or value in Java and lists some example codes to understand the topic.

In Java, to get type of a variable or a value, we can use getClass() method of Object class. This is the only way to do this, unlike JavaScript with the typeof() method to check type.

Since we used the getClass() method of Object class, it works with objects only, not primitives. If you want to get the type of primitives, then first convert them using the wrapper class. Let’s understand with some examples.

Get the Type of a Variable/Value in Java

In this example, we used getClass() to check the type of a variable. Since this variable is a string type, then we can directly call the method. See the example below.

Notice that the getClass() method returns a fully qualified class name, including a package name such as java.lang.String in our case.

public class SimpleTesting  public static void main(String[] args)  String msg = "Hello";  System.out.println(msg);  System.out.println("Type is: "+msg.getClass());  > > 
Hello Type is: class java.lang.String 

Get the Type of Any Variable/Value in Java

In the above example, we used a string variable and got its type similarly; we can also use another type of variable, and the method returns the desired result. See the example below.

In this example, we created two more variables, integer and character, apart from string and used the getClass() method.

package javaexample; public class SimpleTesting  public static void main(String[] args)  String msg = "Hello";  System.out.println(msg);  System.out.println("Type is: "+msg.getClass());  // Integer  Integer val = 20;  System.out.println(val);  System.out.println("Type is: "+val.getClass());  // Character  Character ch = 'G';  System.out.println(ch);  System.out.println("Type is: "+ch.getClass());  > > 
Hello Type is: class java.lang.String 20 Type is: class java.lang.Integer G Type is: class java.lang.Character 

The getClass() method returns a complete qualified name of the class, including the package name. If you wish to get only the type name, you can use the getSimpleName() method that returns a single string. See the example below.

package javaexample; public class SimpleTesting  public static void main(String[] args)  String msg = "Hello";  System.out.println(msg);  System.out.println("Type is: "+msg.getClass().getSimpleName());   // Integer  Integer val = 20;  System.out.println(val);  System.out.println("Type is: "+val.getClass().getSimpleName());   // Character  Character ch = 'G';  System.out.println(ch);  System.out.println("Type is: "+ch.getClass().getSimpleName());  > > 
Hello Type is: String 20 Type is: Integer G Type is: Character 

Related Article — Java Operator

Источник

Java получить тип данных

Learn Latest Tutorials

Splunk tutorial

SPSS tutorial

Swagger tutorial

T-SQL tutorial

Tumblr tutorial

React tutorial

Regex tutorial

Reinforcement learning tutorial

R Programming tutorial

RxJS tutorial

React Native tutorial

Python Design Patterns

Python Pillow tutorial

Python Turtle tutorial

Keras tutorial

Preparation

Aptitude

Logical Reasoning

Verbal Ability

Company Interview Questions

Artificial Intelligence

AWS Tutorial

Selenium tutorial

Cloud Computing

Hadoop tutorial

ReactJS Tutorial

Data Science Tutorial

Angular 7 Tutorial

Blockchain Tutorial

Git Tutorial

Machine Learning Tutorial

DevOps Tutorial

B.Tech / MCA

DBMS tutorial

Data Structures tutorial

DAA tutorial

Operating System

Computer Network tutorial

Compiler Design tutorial

Computer Organization and Architecture

Discrete Mathematics Tutorial

Ethical Hacking

Computer Graphics Tutorial

Software Engineering

html tutorial

Cyber Security tutorial

Automata Tutorial

C Language tutorial

C++ tutorial

Java tutorial

.Net Framework tutorial

Python tutorial

List of Programs

Control Systems tutorial

Data Mining Tutorial

Data Warehouse Tutorial

Javatpoint Services

JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.

  • Website Designing
  • Website Development
  • Java Development
  • PHP Development
  • WordPress
  • Graphic Designing
  • Logo
  • Digital Marketing
  • On Page and Off Page SEO
  • PPC
  • Content Development
  • Corporate Training
  • Classroom and Online Training
  • Data Entry

Training For College Campus

JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 week

Like/Subscribe us for latest updates or newsletter RSS Feed Subscribe to Get Email Alerts Facebook Page Twitter Page YouTube Blog Page

Источник

Читайте также:  Shutdown hooks in java
Оцените статью