[英]How can I access to a public final static list declared into an utility class from another class in a Java application?
[英]How can I instantiate a inner public static final class in java from a different package
我有一个用例,试图从另一个包实例化内部公共static最终类。 我正在尝试这样做,以便可以模拟对单元测试的响应。 我们可以使用模拟服务器,但是,我只想在这种情况下使用模拟对象以提高速度并进行更受控的测试。 这是下面的代码片段:
public class Http {
private final HttpClient client;
@Inject
Http(HttpClient client) {
this.client = client;
}
public Http.Response get(Http.Request request) {
try {
Http.Response response = this.getResponse(this.client.execute(this.createHttpGet(request)));
return response;
} catch (IOException var4) {
throw new RuntimeException(var4);
} catch (URISyntaxException var5) {
throw new RuntimeException(var5);
}
}
private Http.Response getResponse(HttpResponse httpResponse) throws IOException {
Http.Response response = new Http.Response(httpResponse.getStatusLine().getStatusCode());
response.setMessageBody(EntityUtils.toString(httpResponse.getEntity()));
return response;
}
public static final class Response {
private final int statusCode;
private ImmutableMap<String, String> headers;
private String message;
private String messageBody;
Response(int statusCode) {
this.statusCode = statusCode;
}
public int getStatusCode() {
return this.statusCode;
}
public Map<String, String> getHeaders() {
return this.headers;
}
void setHeaders(Map<String, String> headers) {
this.headers = ImmutableMap.builder().putAll(headers).build();
}
public String getMessage() {
return this.message;
}
void setMessage(String message) {
this.message = message;
}
public String getMessageBody() {
return this.messageBody;
}
void setMessageBody(String messageBody) {
this.messageBody = messageBody;
}
public String toString() {
return String.format("HttpResponse{statusCode=%d, headers=%s, message='%s', messageBody='%s'}", this.statusCode, this.headers, this.message, this.messageBody);
}
}
}
您的Http.Response
构造函数需要是公共的,才能从另一个包中实例化。
在这里,由于它的可见性是default
,因此只能从同一包中实例化它。
您似乎出于测试目的需要它。 如果您不想更改可见性,则可以在测试类中创建与Http
类相同的包中的类,仅用于实例化Responses
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.