https://kotlinlang.org logo
Join the conversationJoin Slack
Channels
100daysofcode
100daysofkotlin
100daysofkotlin-2021
advent-of-code
aem
ai
alexa
algeria
algolialibraries
amsterdam
android
android-architecture
android-databinding
android-studio
androidgithubprojects
androidthings
androidx
androidx-xprocessing
anime
anko
announcements
apollo-kotlin
appintro
arabic
argentina
arkenv
arksemdevteam
armenia
arrow
arrow-contributors
arrow-meta
ass
atlanta
atm17
atrium
austin
australia
austria
awesome-kotlin
ballast
bangladesh
barcelona
bayarea
bazel
beepiz-libraries
belgium
berlin
big-data
books
boston
brazil
brikk
budapest
build
build-tools
bulgaria
bydgoszcz
cambodia
canada
carrat
carrat-dev
carrat-feed
chicago
chile
china
chucker
cincinnati-user-group
cli
clikt
cloudfoundry
cn
cobalt
code-coverage
codeforces
codemash-precompiler
codereview
codingame
codingconventions
coimbatore
collaborations
colombia
colorado
communities
competitive-programming
competitivecoding
compiler
compose
compose-android
compose-desktop
compose-hiring
compose-ios
compose-mp
compose-ui-showcase
compose-wear
compose-web
connect-audit-events
corda
cork
coroutines
couchbase
coursera
croatia
cryptography
cscenter-course-2016
cucumber-bdd
cyprus
czech
dagger
data2viz
databinding
datascience
dckotlin
debugging
decompose
decouple
denmark
deprecated
detekt
detekt-hint
dev-core
dfw
docs-revamped
dokka
domain-driven-design
doodle
dsl
dublin
dutch
eap
eclipse
ecuador
edinburgh
education
effective-kotlin
effectivekotlin
emacs
embedded-kotlin
estatik
event21-community-content
events
exposed
failgood
fb-internal-demo
feed
firebase
flow
fluid-libraries
forkhandles
forum
fosdem
fp-in-kotlin
framework-elide
freenode
french
fritz2
fuchsia
functional
funktionale
gamedev
ge-kotlin
general-advice
georgia
geospatial
german-lang
getting-started
github-workflows-kt
glance
godot-kotlin
google-io
gradle
graphic
graphkool
graphql
graphql-kotlin
graviton-browser
greece
grpc
gsoc
gui
hackathons
hacktoberfest
hamburg
hamkrest
helios
helsinki
hexagon
hibernate
hikari-cp
hire-me
hiring
hongkong
hoplite
http4k
hungary
hyderabad
image-processing
india
indonesia
inkremental
intellij
intellij-plugins
intellij-tricks
internships
introduce-yourself
io
ios
iran
israel
istanbulcoders
italian
jackson-kotlin
jadx
japanese
jasync-sql
java-to-kotlin-refactoring
javadevelopers
javafx
javalin
javascript
jdbi
jhipster-kotlin
jobsworldwide
jpa
jshdq
juul-libraries
jvm-ir-backend-feedback
jxadapter
k2-early-adopters
kaal
kafka
kakao
kalasim
kapt
karachi
karg
karlsruhe
kash_shell
kaskade
kbuild
kdbc
kgen-doc-tools
kgraphql
kinta
klaxon
klock
kloudformation
kmdc
kmm-español
kmongo
knbt
knote
koalaql
koans
kobalt
kobweb
kodein
kodex
kohesive
koin
koin-dev
komapper
kondor-json
kong
kontent
kontributors
korau
korean
korge
korim
korio
korlibs
korte
kotest
kotest-contributors
kotless
kotlick
kotlin-asia
kotlin-beam
kotlin-by-example
kotlin-csv
kotlin-data-storage
kotlin-foundation
kotlin-fuel
kotlin-in-action
kotlin-inject
kotlin-latam
kotlin-logging
kotlin-multiplatform-contest
kotlin-mumbai
kotlin-native
kotlin-pakistan
kotlin-plugin
kotlin-pune
kotlin-roadmap
kotlin-samples
kotlin-sap
kotlin-serbia
kotlin-spark
kotlin-szeged
kotlin-website
kotlinacademy
kotlinbot
kotlinconf
kotlindl
kotlinforbeginners
kotlingforbeginners
kotlinlondon
kotlinmad
kotlinprogrammers
kotlinsu
kotlintest
kotlintest-devs
kotlintlv
kotlinultimatechallenge
kotlinx-datetime
kotlinx-files
kotlinx-html
kotrix
kotson
kovenant
kprompt
kraph
krawler
kroto-plus
ksp
ktcc
ktfmt
ktlint
ktor
ktp
kubed
kug-leads
kug-torino
kvision
kweb
lambdaworld_cadiz
lanark
language-evolution
language-proposals
latvia
leakcanary
leedskotlinusergroup
lets-have-fun
libgdx
libkgd
library-development
linkeddata
lithuania
london
losangeles
lottie
love
lychee
macedonia
machinelearningbawas
madrid
malaysia
mathematics
meetkotlin
memes
meta
metro-detroit
mexico
miami
micronaut
minnesota
minutest
mirror
mockk
moko
moldova
monsterpuzzle
montreal
moonbean
morocco
motionlayout
mpapt
mu
multiplatform
mumbai
munich
mvikotlin
mvrx
myndocs-oauth2-server
naming
navigation-architecture-component
nepal
new-mexico
new-zealand
newname
nigeria
nodejs
norway
npm-publish
nyc
oceania
ohio-kotlin-users
oldenburg
oolong
opensource
orbit-mvi
osgi
otpisani
package-search
pakistan
panamá
pattern-matching
pbandk
pdx
peru
philippines
phoenix
pinoy
pocketgitclient
polish
popkorn
portugal
practical-functional-programming
proguard
prozis-android-backup
pyhsikal
python
python-contributors
quasar
random
re
react
reaktive
realm
realworldkotlin
reductor
reduks
redux
redux-kotlin
refactoring-to-kotlin
reflect
refreshversions
reports
result
rethink
revolver
rhein-main
rocksdb
romania
room
rpi-pico
rsocket
russian
russian_feed
russian-kotlinasfirst
rx
rxjava
san-diego
science
scotland
scrcast
scrimage
script
scripting
seattle
serialization
server
sg-user-group
singapore
skia-wasm-interop-temp
skrape-it
slovak
snake
sofl-user-group
southafrica
spacemacs
spain
spanish
speaking
spek
spin
splitties
spotify-mobius
spring
spring-security
squarelibraries
stackoverflow
stacks
stayhungrystayfoolish
stdlib
stlouis
strife-discord-lib
strikt
students
stuttgart
sudan
swagger-gradle-codegen
swarm
sweden
swing
swiss-user-group
switzerland
talking-kotlin
tallinn
tampa
teamcity
tegal
tempe
tensorflow
terminal
test
testing
testtestest
texas
tgbotapi
thailand
tornadofx
touchlab-tools
training
tricity-kotlin-user-group
trójmiasto
truth
tunisia
turkey
turkiye
twitter-feed
uae
udacityindia
uk
ukrainian
uniflow
unkonf
uruguay
utah
uuid
vancouver
vankotlin
vertx
videos
vienna
vietnam
vim
vkug
vuejs
web-mpp
webassembly
webrtc
wimix_sentry
wwdc
zircon
Powered by Linen
reflect
  • d

    dstarcev

    02/14/2018, 4:03 PM
    How do I dynamically instantiate
    Person
    having a map of constructor arguments?
    data class Person(val id: Int, val name: String, val age: Int?)
    val args = mapOf("id" to 1, "name" to "Alice")
    val newPerson = ???
    d
    • 2
    • 3
  • m

    Martin Weigel

    02/16/2018, 8:37 AM
    Already asked this in #getting-started but might be better off here: Hi. I just can't seem to get Kotlin reflection working. I'm looking for a way to manipulate all String properties of an object. Is this possibble with Kotlin reflection?
    d
    • 2
    • 3
  • d

    diesieben07

    03/23/2018, 10:01 AM
    KType.classifier
    will give you that, but it does not have to be a
    KClass
    , it could be a
    KTypeParameter
    . There is also
    KType.jvmErasure
    , which will loose type information though.
    v
    • 2
    • 7
  • a

    aaverin

    03/28/2018, 10:02 AM
    Any way to make this code look nicer with Kotlin?
    try {
            val field = javaClass.getDeclaredField("mShiftingMode")
            field.isAccessible = true
            field.set(this, enable)
        } catch (e: NoSuchFieldException) {
            e.printStackTrace()
        } catch (e: IllegalAccessException) {
            e.printStackTrace()
        }
    I looked into kotlin-reflect, but can’t find a way to make private property public
    r
    • 2
    • 3
  • b

    beholder

    03/28/2018, 5:21 PM
    Unsupported [reference to the synthetic extension property for a Java get/set method]
    - but is it possible get KProperty manually for plain Java class?
    u
    • 2
    • 3
  • v

    v79

    03/30/2018, 7:42 PM
    Can reflection tell me if a KClass is an enum or not? There doesn't seem to be an isEnum method.
    b
    r
    • 3
    • 3
  • b

    bdawg.io

    04/02/2018, 8:27 PM
    Given
    class MyClass(val first: String, val second: Int, val third: Boolean = false)
    , is there a way to reference the variant of the constructor that would provide
    (String, Int) -> MyClass
    as
    KFunction2<String, Int, MyClass>
    ?
    u
    • 2
    • 1
  • v

    v79

    04/07/2018, 3:43 PM
    Given a class definition
    class MyClass(val aList: List<String>)
    the KParameter.type is
    List
    . Is it ever possible for
    List
    to have more than one argument?
    d
    • 2
    • 1
  • v

    v79

    04/12/2018, 6:40 PM
    Here's an unlikely one. Can I cast an
    Any?
    object to an arbitrary
    KClass
    . Here's what I would like to do:
    fun Request.bind(modelClass: KClass<*>): Any? {
    	return WebForm(this,modelClass).get() as modelClass
    }
    I'd like to avoid having to type
    val person: Person = request.bind(Person::class) as Person
    - that's a lot of references to
    Person
    in a single line of code.
    d
    • 2
    • 3
  • d

    dstarcev

    04/17/2018, 6:56 PM
    basically I need some details on how such names are encoded in d1 and d2 properties of
    @Metadata
    g
    u
    e
    • 4
    • 15
  • d

    dstarcev

    04/19/2018, 9:57 AM
    How do I find check if a constructor parameter is also a property?
    u
    e
    • 3
    • 10
  • m

    mbickel

    04/19/2018, 10:53 AM
    I've a question on
    KClass.memberProperties
    - the docs say I get a
    Collection<KProperty1<T, *>>
    , but when I iterate this, the compiler infers
    KProperty1<out T, Any?>
    , which prevents me from calling
    it.get(this)
    on it. Anybody know why?
    u
    • 2
    • 7
  • d

    diesieben07

    04/23/2018, 9:43 AM
    Is there a way to go from a
    KProperty1<T, R>
    to a
    KProperty0<R>
    when I have the receiver object (
    T
    )? I.e., can I "bind" a receiver to a property?
    u
    d
    • 3
    • 4
  • d

    Danny

    05/11/2018, 10:35 PM
    Any kotlin-reflect 1.2.41 users on Windows 10 using stock Windows 10 Defender antivirus not able to build their projects? I've found that recent updates to the Windows 10 Defender antivirus is marking the jar as a trojan. To reproduce, set windows 10 defender as your antivirus and try to run a build that requires kotlin-reflect 1.2.41 as a dependency
    g
    • 2
    • 3
  • o

    orangy

    06/01/2018, 5:37 PM
    https://discuss.kotlinlang.org/t/announcing-kotlinx-metadata-jvm-library-for-reading-modifying-metadata-of-kotlin-jvm-class-files/7980
    ❤️ 3
    d
    • 2
    • 1
  • c

    codyoss

    06/11/2018, 6:49 PM
    is it possible in Kotlin to have a function that take a reified type and do a
    is
    check on
    reified T : Any
    at runtime?
    d
    • 2
    • 4
  • c

    codyoss

    06/22/2018, 4:46 AM
    nvm I just decided to cast to Bar<Any, Any> and suppress the warning. If there is a better way to handle such a thing please do let me know
    d
    b
    • 3
    • 4
  • s

    snowe

    07/17/2018, 5:02 PM
    How do I check if a member is of a nullable class
    d
    • 2
    • 6
  • g

    groostav

    08/04/2018, 5:17 AM
    so if I want to grab a private member my best bet is to after it via javas reflection api, rather than kotlins, _which is so much nicer Q_Q_
    u
    • 2
    • 1
  • s

    ske

    08/08/2018, 11:59 PM
    How much of the reflection API is available without depending on kotlin-reflect?
    u
    • 2
    • 1
  • k

    kennyyi

    08/11/2018, 5:58 AM
    Is there a way to know information of collection?
    fun foo(clazz: Class<*>) {
      // 1. How to know clazz is collection?
      // 2. How to know T of Collection<T> is String?
    }
    
    fun myFunc() {
      val mySet: HashSet<String> = HashSet()
      foo(mySet::class.java)
    }
    d
    • 2
    • 2
  • d

    diesieben07

    08/13/2018, 9:05 PM
    I am trying to obtain the value of every field in an object, but I am apparently unable to do so. I am doing this:
    fun <T : Any> getFieldValues(obj: T): List<Any?> {
        val cls = obj::class
        return cls.memberProperties.map { it.get(obj) }
    }
    But this does not compile, because I am getting
    KClass<out T>
    for
    cls
    . Is there any way to do this in a type-safe manner?
    u
    • 2
    • 2
  • j

    jdiaz

    08/19/2018, 9:01 PM
    Does anyone know how to get the generic type of List<List<T>>? I'd first have List<List<T>> but parsing that would go to List<T> and then T. But I'm getting null in the second operation
    d
    • 2
    • 3
  • g

    Gabriel Machado

    08/24/2018, 12:40 PM
    Class.forName("kotlin.reflect.jvm.internal.ReflectionFactoryImpl")
    is throwing
    java.lang.VerifyError: Bad type on operand stack
    , anyone know how to solve this?
    -.txt
    c
    • 2
    • 3
  • d

    diesieben07

    08/25/2018, 1:39 PM
    When obtaining a
    KFunction
    via a function reference, how do you resolve an "overload resolution ambiguity"? I am trying to get a
    KFunction<String>
    for
    ResultSet::getString
    , but there are two versions of that (
    getString(Int)
    and
    getString(String)
    ). How do I tell the compiler I want the
    Int
    version?
    u
    • 2
    • 5
  • h

    holgerbrandl

    09/24/2018, 9:19 AM
    reflect_on_lambda_body_.kt
    d
    • 2
    • 18
  • r

    ribesg

    10/10/2018, 9:51 AM
    How do I get the value of a
    const val
    property?
    d
    • 2
    • 17
  • j

    juancho

    10/28/2018, 6:36 PM
    Hi everyone, not sure if this was the right channel but I have a question regarding Kotlin Reflection. I posted the question in Stackoverflow: https://stackoverflow.com/questions/53034830/kotlin-reflection-how-to-know-if-a-kotlin-class-is-marked-with-internal-modif The question: I’m autogenerating code with KotlinPoet and Auto Service. I didn’t find any way to know if an annotated class has “internal” modifier so I can create another class with same modifier. For example:
    @MyAnnotation
    internal class Car
    So I thought using Kotlin Reflection I would be able to get this information but no luck. Any clues on how to do it?
    d
    • 2
    • 17
  • s

    SrSouza

    11/01/2018, 2:56 PM
    Hi, I update my project to Kotlin 1.3.0 but the same code in 1.2.60 is giving me a error on 1.3.0
    [11:53:05 ERROR]: Error occurred while enabling KotlinBukkitAPI v0.1.0-SNAPSHOT (Is it up to date?)
    java.lang.IllegalAccessError: tried to access method kotlin.collections.ArraysKt___ArraysJvmKt.copyOfRange([Ljava/lang/Object;II)[Ljava/lang/Object; from class kotlin.reflect.jvm.internal.calls.CallerImpl$Method$Instance
    	at kotlin.reflect.jvm.internal.calls.CallerImpl$Method$Instance.call(CallerImpl.kt:217) ~[?:?]
    	at kotlin.reflect.jvm.internal.KCallableImpl.call(KCallableImpl.kt:106) ~[?:?]
    	at kotlin.reflect.jvm.internal.KMutableProperty1Impl.set(KProperty1Impl.kt:59) ~[?:?]
    	at br.com.devsrsouza.kotlinbukkitapi.dsl.config.KConfig.loadRecursive(ConfigDSL.kt:392) ~[?:?]
    	at br.com.devsrsouza.kotlinbukkitapi.dsl.config.KConfig.loadAndSetDefaultR(ConfigDSL.kt:142) ~[?:?]
    	at br.com.devsrsouza.kotlinbukkitapi.dsl.config.KConfig.loadAndSetDefault(ConfigDSL.kt:96) ~[?:?]
    	at br.com.devsrsouza.kotlinbukkitapi.dsl.config.ConfigDSLKt.loadAndSetDefault(ConfigDSL.kt:63) ~[?:?]
    	at br.com.devsrsouza.kotlinbukkitapi.dsl.config.ConfigDSLKt.loadAndSetDefault$default(ConfigDSL.kt:61) ~[?:?]
    	at br.com.devsrsouza.kotlinbukkitapi.KotlinBukkitAPI.onEnable(KotlinBukkitAPI.kt:25) ~[?:?]
    	at org.bukkit.plugin.java.JavaPlugin.setEnabled(JavaPlugin.java:321) ~[1.8.8.jar:git-Spigot-21fe707-e1ebe52]
    	at org.bukkit.plugin.java.JavaPluginLoader.enablePlugin(JavaPluginLoader.java:340) ~[1.8.8.jar:git-Spigot-21fe707-e1ebe52]
    	at org.bukkit.plugin.SimplePluginManager.enablePlugin(SimplePluginManager.java:405) ~[1.8.8.jar:git-Spigot-21fe707-e1ebe52]
    	at br.com.devsrsouza.pluginlauncher.Main.lambda$onEnable$0(Main.java:32) ~[?:?]
    	at org.bukkit.craftbukkit.v1_8_R3.scheduler.CraftTask.run(CraftTask.java:71) [1.8.8.jar:git-Spigot-21fe707-e1ebe52]
    	at org.bukkit.craftbukkit.v1_8_R3.scheduler.CraftScheduler.mainThreadHeartbeat(CraftScheduler.java:350) [1.8.8.jar:git-Spigot-21fe707-e1ebe52]
    	at net.minecraft.server.v1_8_R3.MinecraftServer.B(MinecraftServer.java:723) [1.8.8.jar:git-Spigot-21fe707-e1ebe52]
    	at net.minecraft.server.v1_8_R3.DedicatedServer.B(DedicatedServer.java:374) [1.8.8.jar:git-Spigot-21fe707-e1ebe52]
    	at net.minecraft.server.v1_8_R3.MinecraftServer.A(MinecraftServer.java:654) [1.8.8.jar:git-Spigot-21fe707-e1ebe52]
    	at net.minecraft.server.v1_8_R3.MinecraftServer.run(MinecraftServer.java:557) [1.8.8.jar:git-Spigot-21fe707-e1ebe52]
    	at java.lang.Thread.run(Thread.java:748) [?:1.8.0_181]
    i
    j
    • 3
    • 9
  • s

    Serge

    11/08/2018, 10:08 PM
    Hi, If I have a package (*.kt file) and have only functions declared in it (not any class besides package itself) - is it possible by using reflection to obtain the list of those declared functions? I have tried to do something like this -
    val o = object{}
    val mm = o.javaClass.declaredMethods
    and
    val mm = o::class
      val ff = mm.declaredMemberFunctions
    but it doesn't return anything. is it possible at all? if so, would the function modifier affect this search (private, public, etc)?
    u
    • 2
    • 2
Powered by Linen
Title
s

Serge

11/08/2018, 10:08 PM
Hi, If I have a package (*.kt file) and have only functions declared in it (not any class besides package itself) - is it possible by using reflection to obtain the list of those declared functions? I have tried to do something like this -
val o = object{}
val mm = o.javaClass.declaredMethods
and
val mm = o::class
  val ff = mm.declaredMemberFunctions
but it doesn't return anything. is it possible at all? if so, would the function modifier affect this search (private, public, etc)?
u

udalov

11/09/2018, 1:43 PM
Unfortunately this is not yet natively supported by Kotlin reflection: https://youtrack.jetbrains.com/issue/KT-16479 At the moment, you can use Java reflection and use `.kotlinFunction`/`.kotlinProperty` to map Java reflection objects to Kotlin:
// FILE: test.kt

import kotlin.reflect.jvm.*

fun foo() = "OK"

fun main() {
    val functions = (object {}).javaClass.enclosingClass.declaredMethods
    val foo = functions.single { it.name == "foo" }.kotlinFunction!!
    println(foo.call()) // OK
}
s

Serge

11/09/2018, 4:37 PM
Thank you, @udalov. I have managed to use java reflection before your post here like this (from within main()) -
::main.javaMethod!!.declaringClass.declaredMethods.filter { it.name.startsWith("foo") }.map {it-> it.name}
👍 1
View count: 4