简体   繁体   English

扩展String(或类似)的Java类

[英]Java Class that extends String (or similar)

This is mainly out of curiosity. 这主要是出于好奇。 How would you (if you can) make a class that mimics String. 你如何(如果可以的话)创建一个模仿String的类。 You can't extend String as it's final so that's a no go, but purely for the interest factor, I thought about creating an object that could be initialized literally ( String s = "string"; ). 你不能扩展String,因为它是final所以这是一个不行,但纯粹为了兴趣因素,我考虑创建一个可以按字面初始化的对象( String s = "string"; )。

Is this possible? 这可能吗? If so, how? 如果是这样,怎么样? If not, why? 如果没有,为什么?

No, it's not possible to introduce your own literal types in Java. 不,不可能在Java中引入自己的文字类型。 The language specification gives the syntax for numeric, character and string literals, and that's it. 语言规范给出了数字,字符和字符串文字的语法,就是这样。

You can't even add your own implicit conversions from an existing type with a literal representation to your own custom types (as you can in C# - as an example of a "close cousin) to Java. 您甚至无法将自己的隐式转换从具有文字表示的现有类型添加到您自己的自定义类型(就像在C#中一样 - 作为Java的“近亲”的示例)。

String is Final, for security reasons. 出于安全原因,String是Final。

However, as of Java 1.4, String has been an implementation of the CharSequence interface. 但是,从Java 1.4开始,String一直是CharSequence接口的实现。 If you write your code in terms of CharSequences, you will be able to run it against any implementation of that interface, String included. 如果您根据CharSequences编写代码,您将能够针对该接口的任何实现运行它,包括String。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM