1

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,457
  • 2
  • 15
  • 25
Martin Mlostek
  • 2,397
  • 1
  • 27
  • 52
  • 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
  • @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
  • @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 acts on the already compiled data.
You can't modify your compilation at runtime, because you aren't programming using a script language. We're talking about Java, and it is a compiled language, which require to be translated in a machine-simpler language that the JVM can interpret faster than the code itself.
You could just manage directly the bytecode of runtime, and this answer offers a good starting point.

Davide Cannizzo
  • 2,434
  • 1
  • 24
  • 31