要将CXF JAX-RS的response.readEntity函数改为通用的方式,可以使用Java泛型来实现。下面是一个示例代码:
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
public class GenericExample<T> {
private Class<T> responseType;
public GenericExample(Class<T> responseType) {
this.responseType = responseType;
}
public T getResponse(String url) {
Client client = ClientBuilder.newClient();
Response response = client.target(url).request(MediaType.APPLICATION_JSON).get();
return response.readEntity(responseType);
}
public static void main(String[] args) {
GenericExample<MyClass> example = new GenericExample<>(MyClass.class);
String url = "https://api.example.com/data";
MyClass myClass = example.getResponse(url);
System.out.println(myClass);
}
}
class MyClass {
private String name;
// other fields and methods
@Override
public String toString() {
return "MyClass{" +
"name='" + name + '\'' +
'}';
}
}
在上面的示例中,我们创建了一个名为GenericExample
的泛型类,其中的getResponse
方法接收一个URL参数,并返回指定类型的响应对象。在main
方法中,我们创建了一个GenericExample
实例,并指定了MyClass
作为响应类型。然后,我们调用getResponse
方法并将URL作为参数传递,最后打印出响应对象。
请注意,上述代码中的MyClass
是一个自定义的类,你需要根据自己的需求替换为实际的响应对象类型。此外,你还需要根据实际情况修改URL和媒体类型等参数。