how to add method to standard java class
-
28-06-2021 - |
题
Is there a way to add a method to a standard Java class, such as Object
?
I know you can't subclass classes like String
which are final, but Object
isn't. I know I could just subclass Object and define a method in the subclass and make all my classes subclasses of that, but I'd rather not have to do that.
I suspect that this is either impossible or I've overlooked something. Thanks in advance for any answers.
解决方案
You can't do this in Java. But other JVM languages are capable of doing so:
in groovy
ExpandoMetaClass
allows adding arbitrary methods to any classin scala implicit conversions can be used to emulate such behaviour in statically-typed manner, see: Inject methods into existing classes
also you can run ruby (jruby) and javascript on top of JVM