Java Reflection make final method non final

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP


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.


Field


// 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())
}





Even if it were possible, what do you think that would help?
– Kayaman
Jan 10 at 16:06





Does that mean its not possible?
– Martin Mlostek
Jan 10 at 16:09





@martynmlostekk It is useless, unless you plan on creating a new class at runtime and load that class.
– Turing85
Jan 10 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 at 16:16







@martynmlostekk in this case, you may want to include this information in your question to avoid the XY-problem.
– Turing85
Jan 10 at 16:19




1 Answer
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.






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Stripe::AuthenticationError No API key provided. Set your API key using “Stripe.api_key = ”

CRM reporting Extension - SSRS instance is blank

Keycloak server returning user_not_found error when user is already imported with LDAP