[英]How to write a function which accepts different object types but perform same operation in Java
I am using import org.apache.http.client.methods.HttpPut and HttpGet to form the headers of my put and get requests. 我正在使用import org.apache.http.client.methods.HttpPut和HttpGet来形成我的put和get请求的标头。 A lot of the headers to be added in these methods are same and I want to avoid writing the same code in both my put and get functions.
这些方法中要添加的许多标头是相同的,我想避免在put和get函数中编写相同的代码。 Is there a way to have a function which accepts both HttpPut or HttpGet objects as parameters and will be able to add headers?
有没有一种方法可以接受HttpPut或HttpGet对象作为参数并能够添加标头? For example:
例如:
HttpGet get= new HttpGet(url);
get = addHeaders(get);
get.setHeader();//custom headers for get requests
HttpPut put = new HttpPut(url);
put = addHeaders(put);
Object addHeaders(Object x) {
x.setHeader();//add the common headers
return x;
}
What is the best way to do this? 做这个的最好方式是什么?
both HttpGet
and HttpPost
has implements the HttpMessage
interface which contains a method setHeader()
so HttpGet
和HttpPost
都实现了HttpMessage
接口,该接口包含方法setHeader()
因此
public void setHeader(HttpMessage msg){
msg.setHeader("xxxx");
}
will do the trick. 会成功的
HttpMessage
is the parent of HttpGet
and HttpPut
. HttpMessage
是HttpGet
和HttpPut
的父HttpPut
。
Try this 尝试这个
HttpMessage addHeaders(HttpMessage x) {
x.setHeader();//add the common headers
return x;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.