2

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.

5
  • You can't add method to standard java class. Commented Aug 26, 2012 at 12:54
  • Well you should do that! The behaviour you are expecting is in Javascript prototypes. Commented Aug 26, 2012 at 12:55
  • Is this for testing or production code? Commented Aug 26, 2012 at 13:03
  • Could you explain why you'd possibly want to do this? Commented Aug 26, 2012 at 13:17
  • Yes I imamgined it was impossible in Java. Initially it is for doing some experiments but if I can get other stuff to go with it to work it would hopefully end up in some OSS software. There are really two reasons I was hoping to add a method to Object. One is because logically it is the best way for other reasons. The other reason is that the method(s) I have in mind crucially rely on the this keyword. However, see below. Commented Aug 26, 2012 at 19:54

1 Answer 1

6

You can't do this in Java. But other JVM languages are capable of doing so:

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the answer. Yes I thought one of the JVM scripting languages might be able to do it. This is acceptable to me. What I should have said is that I wanted a JVM solution (not necessarily Java) so one of the dynamic JVM languages or using reflect or even using a customised Object class file in the classpath would be okay. I'll look at groovy and javascript for sure. However I thought an "in-language" solution would be best from a maintenance perspective. Thanks Tomasz for the answer to all who commented.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.