Reputation: 91
I have a Java class similar to the following one:
public final class Node {
public Node() {}
}
I have learned already how to change change the accessibility of 'final' fields via the reflection API, but is this also possible for classes? Can I turn a final class into a non-final class at runtime?
Upvotes: 6
Views: 2033
Reputation: 191
Edit: Thanks to the comment of @kriegaex. 'accessFlags' field only exists in Class class implementation in Android SDK. Therefore, unless you are developing for Android, this solution will not work for you since such a field does not exist in the first place.
Here is how you can make the class extendable by removing the 'final' modifier:
Class classClass = Class.class;
Field accessFlagsField = classClass.getDeclaredField("accessFlags");
accessFlagsField.setAccessible(true);
Class nodeClass = Node.class;
accessFlagsField.setInt(nodeClass, nodeClass.getModifiers() & ~Modifier.FINAL);
I do not agree with the answers above. One might want to remove the 'final' modifier to extend the class during runtime by using 'ASM' or libraries like 'byte-buddy'. I agree that if it is a final class, it is probably for a good reason but custom business logic may require to do so.
Upvotes: 1
Reputation: 308763
I don't see how this can work, because the compiler will check to see if the class you're trying to make non-final at compile time. You'll get an error if you try to inherit from it.
I think it's fine to ask the question if you're curious, but the larger question to ask yourself is why do you want to do this? Reflection allows you to do a lot of things to get around final, private, etc., but that doesn't mean it's a good idea. If the designer of a 3rd party library thought that final was a good idea, you might be well advised to honor that.
Upvotes: 0
Reputation: 533530
You can re-write a class file using a library like ASM.
There may be no point changing the final
status of a class at runtime as it needs to be non-final at compile time to compile a sub-class.
Upvotes: 4