Can we add extra method in java.lang.Object?

2.4k views Asked by At

We have a set of methods defined in java.lang.Object. And every class extending this class automatically.

How to add a method in java.lang.Object class?

4

There are 4 answers

2
Anders R. Bystrup On BEST ANSWER

No (only by tinkering with rt.jar or bootclasspath), and why would you want to do that when you can write your own class that - by definition - extends Object?

If the "need" arises to add methods to an existing class (in particular something in the JRE libraries) that is usually an indication that your design/object model isn't sound. Show us why you want to do this and we can help you better.

I understand from a comment on another answer that you want to print information about "unknown" objects. This is exactly what toString() is for. If you override that method on your own classes, you can control the output exactly, rather than the usual name@hash. This is of course assuming that you're not throwing just anything into the methods in question, but only classes you control...

Cheers,

3
Aniket Thakur On

No! you cannot add your custom functions in java.lang.Object class.

1
Christian Fries On

As pointed out by others: the answer to your question is No if avoid changing the original code...

I don't know your application, but in case you like to add "Aspects" you might want to take a look to AspectJ: http://en.wikipedia.org/wiki/AspectJ

2
Peter Lawrey On

Technically you can but there is a number of problems.

  • it violates your license agreement for Oracle JDK, possibly others.
  • you have to add your new version to the start of your bootclasspath or endorsed directory which is a pain.
  • you can only add a couple of methods before the JVM crashes. It makes some assumptions about the Object class and some other commonly used classes.

I would only do this for investigation purposes and not use it in production.