Как узнать имя класса

от admin

Узнать имя класса во время исполнения программы

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

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

Это можно реализовать? Можно и boost`ом.

Функция typeid(object) возвращает объект типа type_info с информацией о типе объекта, для которого она вызывается (собственно, о классе). У этого объекта( type_info ) есть метод name() , который и возвращает имя класса. Для использования нужно подключить <typeinfo> .

Так что в итоге для получения имени класса нужно использовать

Или, если функция не является методом класса, передать в typeid сам объект или разыменованный указатель.

Собственные средства c++ не позволяют ничего узнать о контектсте вызова функции.

Стек вызова можно проанализировать с помощью некоторых внешних библиотек / API операционной системы. Например: http://man7.org/linux/man-pages/man3/backtrace.3.html https://msdn.microsoft.com/en-us/library/ms680650%28VS.85%29.aspx . Но для применение этих средств может налагать дополнительные ограничения на собираемый код (сборка с отладочной информацией и т.д.).

Более разумно, ИМХО, передавать контекст вызова явно: это позволит использовать «штатные» средства c++: __FILE__ , __LINE__ , __func__ , . Извлечение контекста можно замаскировать макросом:

Имя класса можно извлечь либо разобрав имя __FUNCTION__ , либо из указателя this :

Но не хочется включать этот обращение к this в макрос, поскольку функции может быть вызвана из контекста, статической функции.

С другой стороны для целей разделения логов может быть достаточно __FILE__ .

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

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

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

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

get_class

Возвращает имя класса, экземпляром которого является объект object .

Список параметров

Тестируемый объект. Внутри класса этот параметр может быть опущен.

Замечание: Начиная с PHP 7.2.0, явная передача null в object запрещена и выдаёт ошибку уровня E_WARNING . Начиная с PHP 8.0.0, при передаче null , выбрасывается исключение TypeError .

Возвращаемые значения

Возвращает имя класса, к которому принадлежит экземпляр object .

Если параметр object опущен внутри класса, будет возвращено имя этого класса.

Если параметр object является экземпляром класса, существующего в пространстве имён, то будет возвращено полное имя с указанием пространства имён.

Ошибки

Если функция get_class() вызывается с чем-либо, кроме объекта, выбрасывается исключение TypeError . До PHP 8.0.0 выдавалась ошибка уровня E_WARNING .

Если функция get_class() вызывается без аргументов вне класса, выбрасывается исключение Error . До PHP 8.0.0 выдавалась ошибка уровня E_WARNING .

Список изменений

Версия Описание
8.0.0 Вызов функции вне класса без каких-либо аргументов вызовет исключение Error . Ранее выдавалась ошибка уровня E_WARNING и функция возвращала значение false .
7.2.0 До этой версии значением по умолчанию для object было null с тем же эффектом, что и отсутствие передачи значения. Теперь null был удалён как значение по умолчанию для object и больше не является допустимым значением.

Примеры

Пример #1 Использование get_class()

class foo <
function name ()
<
echo «Меня зовут » , get_class ( $this ) , «\n» ;
>
>

// создание объекта
$bar = new foo ();

// внешний вызов
echo «Его имя » , get_class ( $bar ) , «\n» ;

// внутренний вызов
$bar -> name ();

Результат выполнения данного примера:

Пример #2 Использование get_class() в родительском классе

abstract class bar <
public function __construct ()
<
var_dump ( get_class ( $this ));
var_dump ( get_class ());
>
>

class foo extends bar <
>

Результат выполнения данного примера:

Пример #3 Использование get_class() с классами в пространствах имён

namespace Foo \ Bar ;

class Baz <
public function __construct ()
<

$baz = new \ Foo \ Bar \ Baz ;

var_dump ( get_class ( $baz ));
?>

Результат выполнения данного примера:

Смотрите также

  • get_called_class() — Имя класса, полученное с помощью позднего статического связывания
  • get_parent_class() — Возвращает имя родительского класса для объекта или класса
  • gettype() — Возвращает тип переменной
  • get_debug_type() — Возвращает имя типа переменной в виде, подходящем для отладки
  • is_subclass_of() — Проверяет, содержит ли объект в своём дереве предков указанный класс либо прямо реализует его

User Contributed Notes 36 notes

::class
fully qualified class name, instead of get_class

<?php
namespace my \ library \ mvc ;

print Dispatcher ::class; // FQN == my\library\mvc\Dispatcher

$disp = new Dispatcher ;

print $disp ::class; // parse error

A lot of people in other comments wanting to get the classname without the namespace. Some weird suggestions of code to do that — not what I would’ve written! So wanted to add my own way.

<?php
function get_class_name ( $classname )
<
if ( $pos = strrpos ( $classname , ‘\\’ )) return substr ( $classname , $pos + 1 );
return $pos ;
>
?>

Also did some quick benchmarking, and strrpos() was the fastest too. Micro-optimisations = macro optimisations!

39.0954 ms — preg_match()
28.6305 ms — explode() + end()
20.3314 ms — strrpos()

(For reference, here’s the debug code used. c() is a benchmarking function that runs each closure run 10,000 times.)

<?php
c (
function( $class = ‘a\b\C’ ) <
if ( preg_match ( ‘/\\\\([\w]+)$/’ , $class , $matches )) return $matches [ 1 ];
return $class ;
>,
function( $class = ‘a\b\C’ ) <
$bits = explode ( ‘\\’ , $class );
return end ( $bits );
>,
function( $class = ‘a\b\C’ ) <
if ( $pos = strrpos ( $class , ‘\\’ )) return substr ( $class , $pos + 1 );
return $pos ;
>
);
?>

People seem to mix up what __METHOD__, get_class($obj) and get_class() do, related to class inheritance.

Here’s a good example that should fix that for ever:

class Foo <
function doMethod () <
echo __METHOD__ . «\n» ;
>
function doGetClassThis () <
echo get_class ( $this ). ‘::doThat’ . «\n» ;
>
function doGetClass () <
echo get_class (). ‘::doThat’ . «\n» ;
>
>

class Bar extends Foo <

class Quux extends Bar <
function doMethod () <
echo __METHOD__ . «\n» ;
>
function doGetClassThis () <
echo get_class ( $this ). ‘::doThat’ . «\n» ;
>
function doGetClass () <
echo get_class (). ‘::doThat’ . «\n» ;
>
>

$foo = new Foo ();
$bar = new Bar ();
$quux = new Quux ();

$foo -> doMethod ();
$bar -> doMethod ();
$quux -> doMethod ();

$foo -> doGetClassThis ();
$bar -> doGetClassThis ();
$quux -> doGetClassThis ();

$foo -> doGetClass ();
$bar -> doGetClass ();
$quux -> doGetClass ();

—doMethod—
Foo::doMethod
Foo::doMethod
Quux::doMethod

—doGetClassThis—
Foo::doThat
Bar::doThat
Quux::doThat

—doGetClass—
Foo::doThat
Foo::doThat
Quux::doThat

If you are using namespaces this function will return the name of the class including the namespace, so watch out if your code does any checks for this. Ex:

<?php
class Foo
<
public function __construct ()
<
echo «Foo» ;
>
>

$test = new Shop \ Foo ();
echo get_class ( $test ); //returns Shop\Foo
?>

/**
* Obtains an object class name without namespaces
*/
function get_real_class($obj) <
$classname = get_class($obj);

if (preg_match(‘@\\\\([\w]+)$@’, $classname, $matches)) <
$classname = $matches[1];
>

Need a quick way to parse the name of a class when it’s namespaced? Try this:

<?php
namespace Engine ;
function parse_classname ( $name )
<
return array(
‘namespace’ => array_slice ( explode ( ‘\\’ , $name ), 0 , — 1 ),
‘classname’ => join ( » , array_slice ( explode ( ‘\\’ , $name ), — 1 )),
);
>
final class Kernel
<
final public function __construct ()
<
echo ‘<pre>’ , print_r ( parse_classname ( __CLASS__ ), 1 ), ‘</pre>’ ;
// Or this for a one-line method to get just the classname:
// echo join(», array_slice(explode(‘\\’, __CLASS__), -1));
>
>
new Kernel ();
?>

Outputs:
Array
(
[namespace] => Array
(
[0] => Engine
)

In Perl (and some other languages) you can call some methods in both object and class (aka static) context. I made such a method for one of my classes in PHP5, but found out that static methods in PHP5 do not ‘know’ the name of the calling subclass’, so I use a backtrace to determine it. I don’t like hacks like this, but as long as PHP doesn’t have an alternative, this is what has to be done:

public function table_name() <
$result = null;
if (isset($this)) < // object context
$result = get_class($this);
>
else < // class context
$result = get_class();
$trace = debug_backtrace();
foreach ($trace as &$frame) <
if (!isset($frame[‘class’])) <
break;
>
if ($frame[‘class’] != $result) <
if (!is_subclass_of($frame[‘class’], $result)) <
break;
>
$result = $frame[‘class’];
>
>
>
return $result;
>

The code in my previous comment was not completely correct. I think this one is.

<?
abstract class Singleton <
protected static $__CLASS__ = __CLASS__;

protected function __construct() <
>

abstract protected function init();

/**
* Gets an instance of this singleton. If no instance exists, a new instance is created and returned.
* If one does exist, then the existing instance is returned.
*/
public static function getInstance() <
static $instance;

if ($instance === null) <
$instance = new $class();
$instance->init();
>

/**
* Returns the classname of the child class extending this class
*
* @return string The class name
*/
private static function getClass() <
$implementing_class = static::$__CLASS__;
$original_class = __CLASS__;

if ($implementing_class === $original_class) <
die(«You MUST provide a <code>protected static \$__CLASS__ = __CLASS__;</code> statement in your Singleton-class!»);
>

With regard to getting the class name from a namespaced class name, then using basename() seems to do the trick quite nicely.

<?php
namespace Foo \ Bar ;

abstract class Baz
<
public function report ()
<
echo
‘__CLASS__ ‘ , __CLASS__ , ‘ ‘ , basename ( __CLASS__ ), PHP_EOL ,
‘get_called_class ‘ , get_called_class (), ‘ ‘ , basename ( get_called_class ()), PHP_EOL ;
>
>

class Snafu extends Baz
<
>

(new Snafu )-> report ();
?>

produces output of .

__CLASS__ Foo\Bar\Baz Baz
get_called_class Foo\Bar\Snafu Snafu

There are discussions below regarding how to create a singleton that allows subclassing. It seems with get_called_class there is now a cleaner solution than what is discussed below, that does not require overriding a method per subclass.

<?php
abstract class MySuperclass <
static private $instances = array();

static public function getInstance (): ACFBlock <
$className = get_called_class ();
if (!isset( self :: $instances [ $className ])) <
self :: $instances [ $className ] = new static();
>
return self :: $instances [ $className ];
>

private function __construct () <
// Singleton
>
>

class MySubclass extends MySuperclass <
>

If you want the path to an file if you have i file structure like this

project -> system -> libs -> controller.php
project -> system -> modules -> foo -> foo.php

and foo() in foo.php extends controller() in controller.php like this

<?PHP
namespace system \ modules \ foo ;

class foo extends \ system \ libs \ controller <
public function __construct () <
parent :: __construct ();
>
>
?>

and you want to know the path to foo.php in controller() this may help you

<?PHP
namespace system \ libs ;

class controller <
protected function __construct () <
$this -> getChildPath ();
>
protected function getChildPath () <
echo dirname ( get_class ( $this ));
>
>
?>

<?PHP
$f = new foo (); // system\modules\foo
?>

Although you can call a class’s static methods from an instance of the class as though they were object instance methods, it’s nice to know that, since classes are represented in PHP code by their names as strings, the same thing goes for the return value of get_class():

<?php
$t -> Faculty ();
SomeClass :: Faculty (); // $t instanceof SomeClass
«SomeClass» :: Faculty ();
get_class ( $t ):: Faculty ();
?>

The first is legitimate, but the last makes it clear to someone reading it that Faculty() is a static method (because the name of the method certainly doesn’t).

well, if you call get_class() on an aliased class, you will get the original class name

class_alias ( ‘Person’ , ‘User’ );

var_dump ( get_class ( $me ) ); // ‘Person’

class A
<
function __construct() <
//parent::__construct();
echo $this->m = ‘From constructor A: ‘.get_class();
echo $this->m = ‘From constructor A:- argument = $this: ‘.get_class($this);

echo $this->m = ‘From constructor A-parent: ‘.get_parent_class();
echo $this->m = ‘From constructor A-parent:- argument = $this: ‘.get_parent_class($this);
>
>
class B extends A
<
function __construct() <
parent::__construct();
echo $this->m = ‘From constructor B: ‘.get_class();
echo $this->m = ‘From constructor B:- argument = $this: ‘.get_class($this);

echo $this->m = ‘From constructor B-parent: ‘.get_parent_class();
echo $this->m = ‘From constructor B-parent:- argument = $this: ‘.get_parent_class($this);
>
>
$b = new B();
//—————-output———————

From constructor A: A
From constructor A:- argument = $this: B
From constructor A-parent:
From constructor A-parent:- argument = $this: A
From constructor B: B
From constructor B:- argument = $this: B
From constructor B-parent: A
From constructor B-parent:- argument = $this: A

Use get_class() to get the name of class ,it will help you get the class name, in case you extend that class with another class and want to get the name of the class to which object is instance of user get_class($object)

Simplest way how to gets Class without namespace

<?php
namespace a \ b \ c \ d \ e \ f ;

public function __toString () <
$class = explode ( ‘\\’ , __CLASS__ );
return end ( $class );
>
>

echo new Foo (); // prints Foo
?>

Attempting various singleton base class methods described on this page, I have created a base class and bridge function that allows it to work without get_called_class() if it’s not available. Unlike other methods listed here, I chose not to prevent use of __construct() or __clone().

<?php
abstract class Singleton <
protected static $m_pInstance ;
final public static function getInstance () <
$class = static:: getClass ();
if(!isset(static:: $m_pInstance [ $class ])) <
static:: $m_pInstance [ $class ] = new $class ;
>
return static:: $m_pInstance [ $class ];
>
final public static function getClass () <
return get_called_class ();
>
>

// I don’t remember where I found this, but this is to allow php < 5.3 to use this method.
if (! function_exists ( ‘get_called_class’ )) <
function get_called_class ( $bt = false , $l = 1 ) <
if (! $bt )
$bt = debug_backtrace ();
if (!isset( $bt [ $l ]))
throw new Exception ( «Cannot find called class -> stack level too deep.» );
if (!isset( $bt [ $l ][ ‘type’ ])) <
throw new Exception ( ‘type not set’ );
>
else
switch ( $bt [ $l ][ ‘type’ ]) <
case ‘::’ :
$lines = file ( $bt [ $l ][ ‘file’ ]);
$i = 0 ;
$callerLine = » ;
do <
$i ++;
$callerLine = $lines [ $bt [ $l ][ ‘line’ ] — $i ] . $callerLine ;
> while ( stripos ( $callerLine , $bt [ $l ][ ‘function’ ]) === false );
preg_match ( ‘/([a-zA-Z0-9\_]+)::’ . $bt [ $l ][ ‘function’ ] . ‘/’ , $callerLine , $matches );
if (!isset( $matches [ 1 ])) <
// must be an edge case.
throw new Exception ( «Could not find caller class: originating method call is obscured.» );
>
switch ( $matches [ 1 ]) <
case ‘self’ :
case ‘parent’ :
return get_called_class ( $bt , $l + 1 );
default:
return $matches [ 1 ];
>
// won’t get here.
case ‘->’ : switch ( $bt [ $l ][ ‘function’ ]) <
case ‘__get’ :
// edge case -> get class of calling object
if (! is_object ( $bt [ $l ][ ‘object’ ]))
throw new Exception ( «Edge case fail. __get called on non object.» );
return get_class ( $bt [ $l ][ ‘object’ ]);
default: return $bt [ $l ][ ‘class’ ];
>

default: throw new Exception ( «Unknown backtrace method type» );
>
>
>

class B extends Singleton <
>

class C extends Singleton <
>

$b = B :: getInstance ();
echo ‘class: ‘ . get_class ( $b );

$c = C :: getInstance ();
echo echo ‘class: ‘ . get_class ( $c );
?>
This returns:
class: b
class: c

Method for pulling the name of a class with namespaces pre-stripped.

<?php
/**
* Returns the name of a class using get_class with the namespaces stripped.
* This will not work inside a class scope as get_class() a workaround for
* that is using get_class_name(get_class());
*
* @param object|string $object Object or Class Name to retrieve name

* @return string Name of class with namespaces stripped
*/
function get_class_name ( $object = null )
<
if (! is_object ( $object ) && ! is_string ( $object )) <
return false ;
>

$class = explode ( ‘\\’ , ( is_string ( $object ) ? $object : get_class ( $object )));
return $class [ count ( $class ) — 1 ];
>
?>

And for everyone for Unit Test goodiness!

<?php
namespace testme \ here ;

public function test ()
<
return get_class_name ( get_class ());
>
>

class GetClassNameTest extends \ PHPUnit_Framework_TestCase
<
public function testGetClassName ()
<
$class = new TestClass ();
$std = new \ stdClass ();
$this -> assertEquals ( ‘TestClass’ , get_class_name ( $class ));
$this -> assertEquals ( ‘stdClass’ , get_class_name ( $std ));
$this -> assertEquals ( ‘Test’ , get_class_name ( ‘Test’ ));
$this -> assertFalse ( get_class_name ( null ));
$this -> assertFalse ( get_class_name (array()));
$this -> assertEquals ( ‘TestClass’ , $class -> test ());
>
>
?>

As noted in bug #30934 (which is not actually a bug but a consequence of a design decision), the «self» keyword is bound at compile time. Amongst other things, this means that in base class methods, any use of the «self» keyword will refer to that base class regardless of the actual (derived) class on which the method was invoked. This becomes problematic when attempting to call an overridden static method from within an inherited method in a derived class. For example:

<?php
class Base
<
protected $m_instanceName = » ;

public static function classDisplayName ()
<
return ‘Base Class’ ;
>

public function instanceDisplayName ()
<
//here, we want «self» to refer to the actual class, which might be a derived class that inherits this method, not necessarily this base class
return $this -> m_instanceName . ‘ — ‘ . self :: classDisplayName ();
>
>

class Derived extends Base
<
public function Derived ( $name )
<
$this -> m_instanceName = $name ;
>

public static function classDisplayName ()
<
return ‘Derived Class’ ;
>
>

$o = new Derived ( ‘My Instance’ );
echo $o -> instanceDisplayName ();
?>

In the above example, assuming runtime binding (where the keyword «self» refers to the actual class on which the method was invoked rather than the class in which the method is defined) would produce the output:

My Instance — Derived Class

However, assuming compile-time binding (where the keyword «self» refers to the class in which the method is defined), which is how php works, the output would be:

My Instance — Base Class

The oddity here is that «$this» is bound at runtime to the actual class of the object (obviously) but «self» is bound at compile-time, which seems counter-intuitive to me. «self» is ALWAYS a synonym for the name of the class in which it is written, which the programmer knows so s/he can just use the class name; what the programmer cannot know is the name of the actual class on which the method was invoked (because the method could be invoked on a derived class), which it seems to me is something for which «self» ought to be useful.

However, questions about design decisions aside, the problem still exists of how to achieve behaviour similar to «self» being bound at runtime, so that both static and non-static methods invoked on or from within a derived class act on that derived class. The get_class() function can be used to emulate the functionality of runtime binding for the «self» keyword for static methods:

<?php
class Base
<
protected $m_instanceName = » ;

public static function classDisplayName ()
<
return ‘Base Class’ ;
>

public function instanceDisplayName ()
<
$realClass = get_class ( $this );
return $this -> m_instanceName . ‘ — ‘ . call_user_func (array( $realClass , ‘classDisplayName’ ));
>
>

class Derived extends Base
<
public function Derived ( $name )
<
$this -> m_instanceName = $name ;
>

public static function classDisplayName ()
<
return ‘Derived Class’ ;
>
>

$o = new Derived ( ‘My Instance’ );
echo $o -> instanceDisplayName ();
?>

Output:
My Instance — Derived Class

I realise that some people might respond «why don’t use just just the class name with ‘ Class’ appended instead of the classDisplayName() method», which is to miss the point. The point is not the actual strings returned but the concept of wanting to use the real class for an overridden static method from within an inherited non-static method. The above is just a simplified version of a real-world problem that was too complex to use as an example.

Получение имени класса в 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().

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

Читать:
Behaveslike win64 generic rc что это

Похожие статьи