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
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 |
|-----------------------|-----------------------|-----------------------|
.get as properties: kotlinlang.org/docs/java-interop.html#getters-and-settersIf it is a java fragment
var fragmentSimpleName = FragmentName::class.java.simpleName as String
Try below solution::-
var name = MainActivity::class.java.canonicalName as String
AClass.class.getName();this code above was invoked in java class , so i cannot use Kotlin syntax like your answer.AClass.class.getName();this code above was invoked in java class , so i cannot use Kotlin syntax like your answer. i want a complete file name,because Class.forName(fragmentName) will be invoked in next. fragmentName should be replace by AClass complete name. but AClass is a Kotlin class now, it throws ClassNotFoundExceptionThis 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.
javaClass?companion object, rather like a variable. In compaion object we can use val TAG = YourClass::class.java.simpleName.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)
}
AClass.class.getPackage().getName();and append that to yourAClass.class.getName();Like so:String location = AClass.class.getPackage().getName() + "." + AClass.class.getName();Class.forName(fragmentName)if fragmentName is a Kotlin class ,it will throws ClassNotFoundException. not matter fragmentName is complete name. so i was confusedval c = Class.forName(fragmentName)?.newInstance() fragment=c as FragmentfragmentName is a KClass complete name, it solves my problem