Getting simpleName() after getClass() in Kotlin

Viewed 11027

In java, I am able to use getClass() and then retrieve simpleName from that class object without any issues.

String tag = someObject.getClass().getSimpleName(); // java code

But when converting to Kotlin, this causes warnings

Call uses reflection API which is not found in compilation classpath. Make sure you have kotlin-reflect.jar in the classpath

The kotlin code is

someObject::class.simpleName!! // kotlin code

What is the proper way of avoiding

kotlin.jvm.KotlinReflectionNotSupportedError ? Needs additional dependency to kotlin-reflect.jar. Maybe would be better use ::class.java.simpleName

3 Answers

Use someObject::class.java.simpleName.

There is couple ways to do this in Kotlin You can receive the name via property - KClass.qualifiedName

val name = AClass::class.qualifiedName;

or through the Class.getName

val name = AClass::class.java.getName();

or you can try with Class.name

val name = AClass::class.java.name;

or Class.canonicalName

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

Lot of answers ask you to enter type your class name, well I have the shortest solution for you.

javaClass.simpleName

You can use the above line anywhere to get the class name, it will return your current class name.

Related