叶钦富
叶钦富

Reputation: 441

Kotlin kotlinClass.class.getName() cannot return package name but only simple class name

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

Answers (5)

LinuxFelipe-COL
LinuxFelipe-COL

Reputation: 411

If it is a java fragment

var fragmentSimpleName = FragmentName::class.java.simpleName as String

Upvotes: 10

Kashif Anwaar
Kashif Anwaar

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

Josep Bigorra
Josep Bigorra

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

holi-java
holi-java

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

Nitin Patel
Nitin Patel

Reputation: 1651

Try below solution::-

var name = MainActivity::class.java.canonicalName as String

Upvotes: 9

Related Questions