开发者

Replacing the default String class with a custom class in Java

I would like to implement my own String class and get Java to use it when I am using double quotes.

It should look like that: MyString s = "foo" and the java.lang.String should not be instantiated.

Is that possible without touching the compiler?

How would it be done?

The reason I am asking is that I need strings in a program that needs to be verified for worst case execution time. In order to verify it, all loops must be bounded (the bound is specified 开发者_运维问答in a comment). Furthermore, I would like to be able to use double quote for convenience, because writing MyString s = new MyString({'f','o','o'}) really decrease readability.


It is not possible whitout touching the compiler.

It is even not possible to subclass String. (You can only provice your own Implementation of java.lang.ChareSequence, but this will not help a lot.)


You can replace the String class. Take the source for String, change it keeping all the method signatures the same, compile it and add it to your bootclasspath. Note: this will replace all Strings, not just those in your code. It may also not compily with your usage license. ;)

If you are worried about readability you can create a helper method which does

MyString s = s("Hello");

If all you want to do is slow down your application you can do a number of things like;

  • use the slowest machine you can find. There are plenty of cheap ones on ebay.
  • disable the JIT.
  • enable debugging.
  • enable profiling and track every method calls and object creation.


You can look for really complicated solutions, like modifying your bytecode at runtime to use MyString everywhere you use String, using a framework like ASM, for example, but good luck with that!

http://asm.ow2.org/

It's probably a better idea to try to get the same result by another way...


Stringer literals are only instantiated once, so don't worry about cost of time.

MyString s = new MyString("foo")

That is fine for your purpose. Only one String instance of "foo" is ever created. (Even if multiple source files contain the "foo" literal). It's almost as if

static private final String $foo = JVM.findOrCreateString('f','o','o');
...
MyString s = new MyString($foo);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜