用Java中的自定义类替换默认的String类
我想实现我自己的 String 类,并让 Java 在我使用双引号时使用它。
它应该看起来像这样: MyString s = "foo"
并且 java.lang.String 不应该被实例化。
这可以在不接触编译器的情况下实现吗?
该怎么做呢?
我问的原因是我需要程序中的字符串,需要验证最坏情况下的执行时间。为了验证它,所有循环都必须有界(界限在注释中指定)。 此外,为了方便起见,我希望能够使用双引号,因为编写 MyString s = new MyString({'f','o','o'})
确实会降低可读性。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
不接触编译器是不可能的。
甚至不可能对 String 进行子类化。 (您只能提供自己的
java.lang.ChareSequence
实现,但这没有多大帮助。)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.)您可以替换 String 类。获取 String 的源代码,更改它以保持所有方法签名相同,编译它并将其添加到您的 bootclasspath 中。注意:这将替换所有字符串,而不仅仅是代码中的字符串。它也可能不符合您的使用许可证。 ;)
如果您担心可读性,您可以创建一个辅助方法,该方法可以执行以下操作:
如果您想做的只是减慢应用程序的速度,您可以执行以下操作:
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
If all you want to do is slow down your application you can do a number of things like;
您可以寻找非常复杂的解决方案,例如在运行时修改字节码,以便在使用 String 的任何地方都使用 MyString,例如使用 ASM 等框架,但祝您好运!
http://asm.ow2.org/
尝试通过另一个人获得相同的结果可能是一个更好的主意方式...
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 文字仅实例化一次,因此不必担心时间成本。
这对你的目的来说很好。仅创建了一个
"foo"
的String
实例。 (即使多个源文件包含"foo"
文字)。几乎就像Stringer literals are only instantiated once, so don't worry about cost of time.
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