All Downloads are FREE. Search and download functionalities are using the official Maven repository.

jvmMain.io.ktor.util.Reflection.kt Maven / Gradle / Ivy

/*
 * Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
 */

package io.ktor.util

import java.util.*

/**
 * Calculates a list of all superclasses for the given class
 */
@Deprecated("To be removed.", level = DeprecationLevel.ERROR)
fun Class<*>.findAllSupertypes(): List> {
    val result = LinkedHashSet>()
    findAllSupertypes(mutableListOf(Pair(this, supertypes())), mutableSetOf(this), result)
    return result.toList()
}

private tailrec fun findAllSupertypes(nodes: MutableList, MutableList>>>, path: MutableSet>, visited: MutableSet>) {
    if (nodes.isEmpty()) return

    val (current, children) = nodes[nodes.lastIndex]
    if (children.isEmpty()) {
        visited.add(current)
        path.remove(current)
        nodes.removeLast()
    } else {
        val next = children.removeLast()
        if (path.add(next)) {
            nodes.add(Pair(next, next.supertypes()))
        }
    }

    findAllSupertypes(nodes, path, visited)
}

private fun Class<*>.supertypes(): MutableList> = when {
    superclass == null -> interfaces?.toMutableList() ?: mutableListOf>()
    interfaces == null || interfaces.isEmpty() -> mutableListOf(superclass)
    else -> ArrayList>(interfaces.size + 1).apply {
        interfaces.toCollection(this@apply)
        add(superclass)
    }
}

private fun  MutableList.removeLast(): T = removeAt(lastIndex)




© 2015 - 2025 Weber Informatics LLC | Privacy Policy