Java Kotlin kotlinClass.class.getName() 不能返回包名而只能返回简单的类名
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44535168/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Kotlin kotlinClass.class.getName() cannot return package name but only simple class name
提问by u8157970
AClass.class.getName();
AClass.class.getName();
if AClass is a java class, this method will return package name and class name. but when i convert AClass java file to Kotlin file ,it will only return a class name. so system cannot find this class path
如果 AClass 是一个 java 类,这个方法将返回包名和类名。但是当我将 AClass java 文件转换为 Kotlin 文件时,它只会返回一个类名。所以系统找不到这个类路径
the code above
上面的代码
回答by Nitin Patel
Try below solution::-
尝试以下解决方案::-
var name = MainActivity::class.java.canonicalName as String
回答by holi-java
there are many ways to get the full qualified name of a java Class
in kotlin:
有很多方法可以Class
在 kotlin 中获取Java 的全限定名:
get name via the property KClass.qualifiedName
:
通过属性获取名称KClass.qualifiedName
:
val name = AClass::class.qualifiedName;
ORget name via the property Class.name
:
或通过属性获取名称Class.name
:
val name = AClass::class.java.name;
ORget name via the method Class#getName
:
或通过方法获取名称Class#getName
:
val name = AClass::class.java.getName();
the table of the qualified name of a class as below:
类的限定名表如下:
|-----------------------|-----------------------|-----------------------|
| | Class | Anonymous Class |
|-----------------------|-----------------------|-----------------------|
| KClass.qualifiedName | foo.bar.AClass | null |
|-----------------------|-----------------------|-----------------------|
| Class.name | foo.bar.AClass | foo.bar.AClass |
|-----------------------|-----------------------|-----------------------|
| Class.getName() | foo.bar.AClass | foo.bar.AClass |
|-----------------------|-----------------------|-----------------------|
回答by LinuxFelipe-COL
If it is a java fragment
如果是java片段
var fragmentSimpleName = FragmentName::class.java.simpleName as String
回答by Josep Jesus Bigorra Algaba
Maybe I am a little bit late for the party, but I do it using hash code of the new instance of the fragment. It is an Int so allows all kinds of tests.
也许我参加派对有点晚了,但我使用片段的新实例的哈希码来完成它。它是一个 Int,因此允许进行各种测试。
private val areaFragment by lazy { Area_Fragment.newInstance() }
var fragmentHashCode = fragment.hashCode()
when (fragmentHashCode) {
areaFragment.hashCode() -> {
myNavigationView.setCheckedItem(R.id.nav_area)
}
回答by Kashif Anwaar
This is what I use to get class-name.
这就是我用来获取类名的方法。
val TAG = javaClass.simpleName
For Android developer's, it's very useful to declare as a field, and call to print logs.
对于 Android 开发者来说,声明为一个字段,并调用打印日志是非常有用的。