简体   繁体   English

如何编写一个接受不同对象类型但在Java中执行相同操作的函数

[英]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 HttpGetHttpPost都实现了HttpMessage接口,该接口包含方法setHeader()因此

public void setHeader(HttpMessage msg){
      msg.setHeader("xxxx");
}

will do the trick. 会成功的

HttpMessage is the parent of HttpGet and HttpPut . HttpMessageHttpGetHttpPut的父HttpPut

Try this 尝试这个

HttpMessage addHeaders(HttpMessage x) {
   x.setHeader();//add the common headers
   return x;
}

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

相关问题 如何编写可以接受多种类型的函数? - How can you write a function that accepts multiple types? Java如何创建一个接受两个列表类型的方法,而不是同时 - Java How to make a method that accepts two list types, not at the same time 如何编写一个接受文字数组的通用函数 - How to write a generic function which accepts arrays of literals 在 Java 中接受两种不同数据类型的类? - A class that accepts two different data types in Java? JAVA 方法在同一个类和同一个实现中但是不同的对象类型作为参数 - JAVA methods in same class and same implementation but different object types as parameter 如何创建一个接受未知类类型并返回正确对象的辅助方法 - How do I create a helper method which accepts unknown class types and return the correct object 执行与Java中的Linux管道相同的操作? - perform same operation as linux pipe in java? 如何在 Java 中编写一个通用的函数以接收具有不同键类型的映射参数? - How to write a function in Java generalized to take in a map parameter that has different key types? 单个泛型参数同时接受两种不同的类型 - Single generic parameter accepts two different types at the same time Java - 如何比较不同对象类型的列表 - Java - How to compare list of different Object types
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM