简体   繁体   中英

Java Reflection make final method non final

I know the way to make a Field non-final via Reflection. But is there a way to make a method non-final? Somehow the same approach does not work.

// make all methods non-final

    Clazz.javaClass.declaredMethods.forEach { method ->
        method.isAccessible = true
        val modifiersField = method.javaClass.getDeclaredField("modifiers")
        modifiersField.isAccessible = true
        modifiersField.setInt(method, modifiersField.modifiers and Modifier.FINAL.inv())
    }

It's impossible because reflection just read the compiled program, which can't be modified at runtime, because Java is a compiled language, not a scripting language.

You can, however, dynamically generate and load classes, like this .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM