2

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())
    }
paulina_glab
  • 2,467
  • 2
  • 16
  • 25
Martin Mlostek
  • 2,755
  • 1
  • 28
  • 57
  • 1
    Even if it were possible, what do you think that would help? – Kayaman Jan 10 '18 at 16:06
  • Does that mean its not possible? – Martin Mlostek Jan 10 '18 at 16:09
  • @martynmlostekk It is useless, unless you plan on creating a new class at runtime and load that class. – Turing85 Jan 10 '18 at 16:11
  • 1
    @Turing85 Well, let me decide if its useful or not (_and yes, I am creating a copy of that class in runtime with modified accessibility_). Possible or not, thats the question. – Martin Mlostek Jan 10 '18 at 16:16
  • 1
    @martynmlostekk in this case, you may want to include this information in your question to avoid the [XY-problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). – Turing85 Jan 10 '18 at 16:19

1 Answers1

1

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.

Davide Cannizzo
  • 2,826
  • 1
  • 29
  • 31