Reputation: 441
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
the code above
Upvotes: 34
Views: 40253
Reputation: 411
If it is a java fragment
var fragmentSimpleName = FragmentName::class.java.simpleName as String
Upvotes: 10
Reputation: 798
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.
Upvotes: 6
Reputation: 833
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.
private val areaFragment by lazy { Area_Fragment.newInstance() }
var fragmentHashCode = fragment.hashCode()
when (fragmentHashCode) {
areaFragment.hashCode() -> {
myNavigationView.setCheckedItem(R.id.nav_area)
}
Upvotes: 1
Reputation: 30676
there are many ways to get the full qualified name of a java Class
in kotlin:
get name via the property KClass.qualifiedName
:
val name = AClass::class.qualifiedName;
OR get name via the property Class.name
:
val name = AClass::class.java.name;
OR get name via the method 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$1 |
|-----------------------|-----------------------|-----------------------|
| Class.getName() | foo.bar.AClass | foo.bar.AClass$1 |
|-----------------------|-----------------------|-----------------------|
Upvotes: 55
Reputation: 1651
Try below solution::-
var name = MainActivity::class.java.canonicalName as String
Upvotes: 9