TL;DR
--From KClass
which can be taken by reflection of Kotlin
, the argument name of the constructor can be taken with the original name.
--From the Class
that can be taken by the reflection of Java
, the argument name of the constructor can only be taken as "ʻarg0, ʻarg1
, ʻarg2... " --Even if you get the
KClass from the code whose original is
Java, the argument name of the constructor will be "ʻarg0
, ʻarg1, ʻarg2
..." and the original argument name cannot be taken.
Extract the argument name of the constructor from the following class.
data class Data(val sampleInt: Int, val sampleString: String)
You can do it in the following two lines.
val clazz: KClass<Data> = Data::class
val parameterNames: List<String> = clazz.constructors.first().parameters.map { it.name }
println(parameterNames) // -> [sampleInt, sampleString]
I will supplement it with the reflection of Java
(I am doing it with Java8
, it seems that there are changes around the reflection in later versions, but I can not follow it).
It will be as follows.
val clazz: Class<Data> = Data::class.java
val parameterNames: List<String> = clazz.constructors.first().parameters.map { it.name }
println(parameterNames) // -> [arg0, arg1]
Do it for the following Java
class.
@Getter //Assumption generated by lombok
public class JavaData {
private final Integer sampleInt;
private final String sampleStr;
public JavaData(Integer sampleInt, String sampleStr) {
this.sampleInt = sampleInt;
this.sampleStr = sampleStr;
}
}
As shown below, the argument name cannot be taken.
val clazz: KClass<JavaData> = JavaData::class
val parameterNames: List<String> = clazz.constructors.first().parameters.map { it.name }
println(parameterNames) // -> [arg0, arg1]
Recommended Posts