java 如何创建 String 类副本?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2068570/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 19:14:00  来源:igfitidea点击:

How to create a String class replica?

javastring

提问by Thunderhashy

I need to create a class with exactly the same methods as java.lang.String.

我需要创建一个与java.lang.String.

What is the best way to do this in Java?

在 Java 中执行此操作的最佳方法是什么?

I know that I can't extend String class as it is final. I am not looking at solutions where I need to copy the source code of java.lang.String. For example, assume that I need the functionality length()within my custom class named MyString, which has a corresponding 'myLength()` method.

我知道我不能按原样扩展 String 类final。我不是在寻找需要复制java.lang.String. 例如,假设我需要length()名为 的自定义类中的功能,该类MyString具有相应的“myLength()”方法。

What is the best way to implement myLength()?

什么是最好的实施方式myLength()

I am not looking at various algorithms to find out the length of a string but to reuse String's length()method. Now once I have MyStringclass ready, I should be able to use it anywhere for my custom manipulations.

我不是在寻找各种算法来找出字符串的长度,而是要重用Stringlength()方法。现在一旦我MyString准备好了课程,我应该可以在任何地方使用它来进行我的自定义操作。

采纳答案by Fabian Steeg

From your question it sounds like the thing you are looking for is simple delegation:

从您的问题中,听起来您正在寻找的是简单的委托

class MyString {

  String delegate; // The actual string you delegate to from your class

  public MyString(String delegate) {
    this.delegate = delegate; // Assign the string that backs your class
  }

  int length() {
    return delegate.length(); // Delegate the method call to the string
  }

  // other methods that delegate to the string field
}

回答by Paul Wagland

Going through the various answers here, and the askers updates and clarifications, it appears that what the asker wants is a class that looks, smells and sounds like a String, but is not.

通过这里的各种答案,以及提问者的更新和澄清,提问者想要的是一个看起来、闻起来和听起来都像字符串的类,但实际上不是。

That is they would like to be able to do:

那就是他们希望能够做到的:

MyString string = "String!!";

This cannot work, since java.lang.Stringis a final class, and so every "String"that the compiler produces will be a java.lang.Stringobject, since this is not a MyStringobject they cannot be assigned to each other.

java.lang.String是行不通的,因为它是一个最终类,所以"String"编译器产生的每一个都是一个java.lang.String对象,因为这不是一个MyString对象,它们不能相互分配。

In weakly typed languages you would be able to create such a class, since if a class looks, smells and sounds like a duck, then to all intents and purposes, it is a duck. Java, however, is a strongly typed language, and a duck is only a duck if it happens to be from the Anatidae family of birds.

在弱类型语言中,您将能够创建这样一个类,因为如果一个类看起来、闻起来和听起来像一只鸭子,那么就所有意图和目的而言,它就是一只鸭子。然而,Java 是一种强类型语言,如果鸭子碰巧来自鸭科鸟类,那么它只是鸭子。

回答by TBH

Since finalclasses cannot be subclassed, create a new class that has aStringinstance inside and operate on this object.

由于final类不能被子类化,因此创建一个内部String实例的新类并对该对象进行操作。

public class MyString {
  private String s;

  public MyString( String s ) {
    setInternalString( s );
  }

  public int myLength() {
    return getInternalString().length();
  }

  private void setInternalString( String s ) {
    this.s = s;
  }

  private String getInternalString() {
    return this.s == null ? "" : this.s;
  }
}

回答by ZoFreX

Proxydesign pattern, I guess. It's a stupid question, though (not a reflection on the asker, but on the person that asked him it in a job interview). Possibly the person asking you didn't realise that String is final? Otherwise I can't think why they would even ask.

我猜是代理设计模式。不过,这是一个愚蠢的问题(不是对提问者的反映,而是对在求职面试中问他的人的反映)。可能问你的人没有意识到 String 是最终的?否则我想不出他们为什么会问。

回答by erickson

I assume you mean java.lang.String. However, you can't replace Stringwith your own class. You can make another class with the same methods (by copying the source code and changing the package declaration), but you won't be able to pass instances of that class to methods that require a String.

我猜你的意思是java.lang.String。但是,您不能String用自己的类替换。您可以使用相同的方法创建另一个类(通过复制源代码并更改包声明),但您将无法将该类的实例传递给需要String.

Which brings up an important question: why do you think you want to do this?

这就引出了一个重要的问题:你认为你为什么要这样做?

回答by Yishai

Make a new class (it will need a different package, of course, implement the same interface and add all the public methods from the String class (read the javadoc to make sure you got everything).

创建一个新类(它需要一个不同的包,当然,实现相同的接口并添加 String 类中的所有公共方法(阅读 javadoc 以确保您获得了所有内容)。

I have to assume this is homework.

我必须假设这是家庭作业。

回答by OscarRyz

You may use the refactoring: Replace inheritance with delegation, which basically is ( as shown in previous answers ) to create an instance variable of the desired type and implement all its methods in the new class and passing the message to them.

您可以使用重构:用委托替换继承,这基本上是(如前面的答案所示)创建所需类型的实例变量并在新类中实现其所有方法并将消息传递给它们。

Create a field for the superclass, adjust methods to delegate to the superclass, and remove the subclassing.

为超类创建一个字段,调整方法以委托给超类,并删除子类化。

https://www.refactoring.com/catalog/repInherWithDel.gif

https://www.refactoring.com/catalog/repInherWithDel.gif

You'll notice this is a lot of typing, that's when a good IDE comes handy.

您会注意到这是大量输入,这时一个好的 IDE 就派上用场了。

The following video shows how IntelliJ IDEA 9 does it.

以下视频展示了 IntelliJ IDEA 9 如何做到这一点。

回答by BigMikeW

If you just want to override a portion of the String behaviour you could try using a dynamic proxy. Look up java.lang.reflect.Proxyin the API.

如果您只想覆盖 String 行为的一部分,您可以尝试使用动态代理。java.lang.reflect.Proxy在 API 中查找。