Pacerier
Pacerier

Reputation: 89663

How do we modify the source of original Java classes?

Hi all I was wondering if I could modify and recompile a Java base class?

I would like to add functions to existing classes and be able to call these functions.

For example, I would like to add a function to java.lang.String, recompile it and use it for my project:

public char[] getInternalValue(){
      return value;
}

I was wondering how do we go about doing that?

Upvotes: 1

Views: 100

Answers (3)

user unknown
user unknown

Reputation: 36229

If you do it, you get incompatible with the java.lang.String class, and with all classes, relying on java.lang.String, which is very, very rarely a good idea.

A second problem could be the license. For self-studying it is perfectly fine, but if you publish your code (compiled or in source) you should read the license terms carefully before.

Since the String class is declared final, you can't even inherit from String, and implement your PacerierString, which seems useful at first sight. But there are so many people, who would have implemented their little helpers, that we would get a lot of SpecialString classes from everywhere.

A common practice would be people, writing a class Foo, and adding a method

 public Foo toFoo () {
     // some conversion for String representation of Foo
 }

to their UniversalToolString.

You may, however, write a Wrapper, which contains a String. You might not pass your Wrapper to a method, which expects a String, but you would need to call its 'toString ()' method, if that happens to be a good candidate for that purpose.

   Foo foo = new Foo ("foobar", 42);
   foo.setMagic (foo.toString ().length); 

Upvotes: 2

ninesided
ninesided

Reputation: 23273

What you're referring to is called "monkey patching". It's possible in Java, but it isn't advisable and the results can be... uhh interesting. You can download the source for the String class, pop it into a JAR and prepend the bootclasspath with:

-Xbootclasspath/p:MonkeyPatchedString.jar

to replace the built-in String class with your own.

There's an interesting paper on this very subject here.

Upvotes: 2

MeBigFatGuy
MeBigFatGuy

Reputation: 28578

Don't do that.

If you want to be evil, you can use reflection to access the byte array of a string. But of course there's no guarantee that that field will exist in the future as is... ok, it probably will, but caveat emptor.

Upvotes: 1

Related Questions