Java 不同 类 中的构造函数用法

Java constructor usage in different classes

我正在使用构造函数在与构造函数本身不同的 class 中初始化对象。构造函数获取一个字符串和 returns 一个对象实例。但是如何从创建对象的 class 获取字符串到定义构造函数的 class ? 我的项目是这样的:

class构造函数:

public class UriParserImplementation implements UriParser {

@Override
public Uri parse() {    
    return null;
}
public UriParserImplementation(String uri) {
}
}

这是class使用带有字符串的构造函数来创建对象实例:

public final class UriParserFactory {
    public static UriParser create(String uri) {
        UriParser parser = new UriParserImplementation(uri);
        return parser;
    }
}

我想在 UriParserImplementation 中使用 UriParserFactory 使用的字符串,但我不知道该怎么做。

But how do I get the string from the class creating the object to the class where the constructor is defined?

组件需要将字符串保存在字段中,需要调用获取字符串的方法。这没有什么神奇的,这是你必须自己编写代码的东西。

如果我没理解错的话,你想将 uri 字符串传递给 UriParserImplementation 的构造函数,并能够在创建实例之后在 UriParserImplementation 中访问它?

如果是这样,你需要在UriParserImplementationclass中添加一个attribute/field,并在构造函数中初始化:

public class UriParserImplementation implements UriParser {
    String originalUri;

    public UriParserImplementation(String uri) {
        originalUri = uri;
    }

    public parse() {
        // you can access originalUri here
    }