Java Class中的规范名称,简单名称和类名有什么区别? [英] What is the difference between canonical name, simple name and class name in Java Class?

查看:419
本文介绍了Java Class中的规范名称,简单名称和类名有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中,它们之间有什么区别:

In Java, what is the difference between these:

Object o1 = ....
o1.getClass().getSimpleName();
o1.getClass().getName();
o1.getClass().getCanonicalName();

我已多次检查过Javadoc,但这从未解释过。
我也运行了一个测试,并没有反映调用这些方法背后的任何实际意义。

I have checked the Javadoc multiple times and yet this never explains it well. I also ran a test and that didn't reflect any real meaning behind the way these methods are called.

推荐答案

如果您对某些事情不确定,请先尝试编写测试。

If you're unsure about something, try writing a test first.

我这样做了:

//primitive
System.out.println(int.class.getName());
System.out.println(int.class.getCanonicalName());
System.out.println(int.class.getSimpleName());

System.out.println();

//class
System.out.println(String.class.getName());
System.out.println(String.class.getCanonicalName());
System.out.println(String.class.getSimpleName());

System.out.println();

//inner class
System.out.println(HashMap.SimpleEntry.class.getName());
System.out.println(HashMap.SimpleEntry.class.getCanonicalName());
System.out.println(HashMap.SimpleEntry.class.getSimpleName());        

System.out.println();

//anonymous inner class
System.out.println(new Serializable(){}.getClass().getName());
System.out.println(new Serializable(){}.getClass().getCanonicalName());
System.out.println(new Serializable(){}.getClass().getSimpleName());

打印:


int
int
int

java.lang.String
java.lang.String
String

java.util.AbstractMap$SimpleEntry
java.util.AbstractMap.SimpleEntry
SimpleEntry

ClassnameTest$1
null

最后一个块中有一个空行,其中 getSimpleName 返回一个空字符串。

There's an empty line in the last block where getSimpleName returns an empty string.

看到这个的结果是:


  • 名称是你的名字d用于动态加载类,例如,使用默认的 ClassLoader 调用 Class.forName

  • 规范名称是将在import语句中使用的名称,并唯一标识该类。在 toString 或记录操作期间可能很有用。

  • 简单名称松散地识别该类,在 toString 或记录操作期间非常有用但不保证是唯一的。

  • the name is the name that you'd use to dynamically load the class with, for example, a call to Class.forName with the default ClassLoader.
  • the canonical name is the name that would be used in an import statement and uniquely identifies the class. Might be useful during toString or logging operations.
  • the simple name loosely identifies the class, again might be useful during toString or logging operations but is not guaranteed to be unique.

这篇关于Java Class中的规范名称,简单名称和类名有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆