Java — get the current class name?
To get the current class name in Java, you can use the getClass() method of the Object class, which returns a Class object that represents the runtime class of the object.
Here is an example of how to get the current class name in Java:
This code gets the Class object for the Main class using the .class notation and then calls the getName() method to get the name of the class as a String .
If you want to get the class name of an object at runtime, you can use the getClass() method of the object. For example:
This code creates an instance of the Main class and gets its Class object using the getClass() method. It then calls the getName() method to get the name of the class as a String .
Метод getClass
А теперь самое интересное. Мы познакомимся с классом Class и немного с Reflection.
Как ты уже, наверное, успел понять, в Java все является объектом. А что нужно для объекта? Что есть у каждого объекта и определяет саму его суть?
— Правильно! Молодец. У каждого объекта есть класс. Но вернемся к объектам. Некоторые объекты полностью содержат какую-то сущность, другие же просто помогают ей управлять.
Ко вторым можно отнести FileOutputStream или Thread. Когда ты создаешь объект Thread, новая нить не создается. Ее создает Java-машина после вызова метода start(). Этот объект просто помогает управлять процессом.
Так же и FileOutputStream: файл хранится на диске и его хранением и доступом к нему управляет ОС. Но мы можем взаимодействовать с ним посредством объектов типа File, при опять-таки помощи Java-машины.
— Да, я это понял уже.
— Так вот, для взаимодействия с классами есть специальный класс и называется он — Class.
— Не трудно было догадаться.
— Ага. Каждый раз, когда Java-машина загружает в память новый класс, она создает объект типа Class, посредством которого можно получить некоторую информацию о загруженном классе.
К каждому классу и объекту привязан такой «объект класса».
Пример | Описание |
---|---|
Получение «объект класса» у класса Integer. | |
Получение «объект класса» у класса int. | |
Получение «объект класса» у объекта типа String. | |
Получение «объект класса» у объекта типа Object. |
— Ух ты, как интересно.
А почему ты пишешь clazz, а не class?
— А ты помнишь, что слово class – это ключевое слово в Java и использовать его для именования переменных нельзя?
— Да, я это знаю, знаю. Только забыл.
— Ты где-нибудь уже использовал объект Class?
— Да, мы использовали его, когда писали свою реализацию метода equals.
— Да, можно сравнить – одинаковые ли у объектов классы, если воспользоваться методом getClass().
— А что можно делать с этим объектом?
Код на Java | Описание |
---|---|
Получить имя класса. | |
Получить класс по имени. | |
Сравнить классы у объектов. |
— Интересно, но не так круто, как я думал.
— Хочешь, чтобы было круто? Есть еще Reflection. Reflection – это очень круто.
— А что такое Reflection?
— Reflection – это способность класса получить информацию о самом себе. В Java есть специальные классы: Field – поле, Method – метод, по аналогии с Class для классов. Т.к. объект типа Class дает возможность получить информацию о классе, то объект типа Field–получить информацию о «поле класса», а Method–о «методе класса». И вот что с ними можно делать:
Get Class Name in Java
This tutorial teaches how to get the class name in Java using four methods. There are many cases where we may want to get the class name in Java.
Get Class Name Using class.getSimpleName() in Java
This is the most used way to get a class’s name. In the following example, we have two classes: GetClassName with the main() method, and another class is ExampleClass .
In the GetClassName class, we use ExampleClass.class to get the information of the class. It returns a Class instance of type ExampleClass . Now we can call getSimpleName() using the classNameInstance that will return only the class name as a String.
Get Class Name of an Anonymous Class Using getName()
An inner class without any name is called an Anonymous class. In this example, we will learn how to get a class name if it is anonymous or check if a class has an anonymous class. Below, we create an interface Example to instantiate the anonymous class. In GetClassName , we instantiate the class without a name using the interface and implement the function printMessage() .
In order to get the class name, we use example.getClass() , but as there is no name of the class, we get an instance of type Class<?> . Then we use classNameInstace to call getName() that returns the name of the class. As the output shows, we get the parent class name GetClassName with $1 appended, representing the anonymous class.
Get Name of Class Using Thread.currentThread().getStackTrace()[1].getClassName()
In the last example, we use the Thread class to get the current running thread using currentThread() that gives us access to the stack dump and all the invocations in the thread. getStackTrace() returns an array of stack elements from which we get the second item of the array and call getClassName() to get the class name of the invocation.
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
В этом посте будет обсуждаться, как определить имя класса базового класса объектов в Java.
1. Класс get*Name() методы
Самый простой способ — вызвать getClass() метод, возвращающий имя класса или интерфейс, представленный объектом, не являющимся массивом. Мы также можем использовать getSimpleName() или же getCanonicalName() , который возвращает простое имя (как в исходном коде) и каноническое имя базового класса соответственно. getTypeName() является недавним дополнением к JDK в Java SE 8, которое внутренне вызывает getClass() .