getClass().getSimpleName() 在同一个类中获取的字符串,值相等,但地址值不同,下面是源码介绍:
public String getSimpleName() {
if (isArray())
return getComponentType().getSimpleName()+"[]";
if (isAnonymousClass()) {
return "";
}
if (isMemberClass() || isLocalClass()) {
// Note that we obtain this information from getInnerClassName(), which uses
// dex system annotations to obtain the name. It is possible for this information
// to disagree with the actual enclosing class name. For example, if dex
// manipulation tools have renamed the enclosing class without adjusting
// the system annotation to match. See http://b/28800927.
return getInnerClassName();
}
String simpleName = getName();
final int dot = simpleName.lastIndexOf(".");
if (dot > 0) {
return simpleName.substring(simpleName.lastIndexOf(".")+1); // strip the package name
}
return simpleName;
}
有的时候需要注意这么一点小小的细节,友盟的分析SDK中设计下列方法:
MobclickAgent.onPageStart(getClass().getSimpleName().intern());
MobclickAgent.onPageEnd(getClass().getSimpleName().intern());
onPageStart方法中对得到的String进行了 == 方式的处理,如果直接给getClass().getSimpleName()给它,将使得两个方法定义的名字不同导致出现问题
onPageStart与onPageEnd传入参数不一致
这里使用到intern()方法对参数进行转化下面介绍intern():
存在于.class文件中的常量池,在运行期被JVM装载,并且可以扩充。
String的intern()方法就是扩充常量池的一个方法;当一个String实例str调用intern()方法时,
Java查找常量池中是否有相同Unicode的字符串常量,如果
有,则返回其的引用,如果没有,则在常量池中增加一个Unicode等于str的字符串并返回它的引用
网友评论