请考虑以下代码:
public class Context {
private final Class<?> clazz;
private final String resource;
private final com.thirdparty.Context context;
public Context(final String resource, final Class<?> clazz) {
this.clazz = clazz;
this.resource = resource;
this.context = com.thirdparty.Context.newInstance(this.clazz);
}
public String marshall(final Object element) {
return this.context.marshall(element);
}
public Object unmarshall(final String element) {
return this.context.unmarshall(element);
}
}
Context context = new Context("request.xsd", Request.class);
// Marshall
Request request = new Request();
String xml = context.marshall(request);
// Unmarshall
Request roundTrip = Request.cast(context.unmarshall(xml));
Run Code Online (Sandbox Code Playgroud)
我试图用泛类版本的Context类替换它:
public class Context<T> {
private final Class<T> clazz;
private final String resource;
private final com.thirdparty.Context context;
public Context(final String resource) {
this.clazz = initHere(); // <== HOW ??
this.resource = resource;
this.context = com.thirdparty.Context.newInstance(this.clazz);
}
public String marshall(final T element) {
return this.context.marshall(element);
}
public T unmarshall(final String element) {
return this.clazz.cast(this.context.unmarshall(element));
}
}
Context<Request> context = new Context<>("request.xsd");
// Marshall
Request request = new Request();
String xml = context.marshall(request);
// Unmarshall
Request roundTrip = context.unmarshall(xml);
Run Code Online (Sandbox Code Playgroud)
因此,我不会将.class作为参数传递给构造函数,而unmarshall方法会自动转换返回对象.
我需要知道传递给newInstance()方法的T类,并调用cast()方法.即T.class或T.getClass().
在我的例子中,我试图在构造函数中初始化clazz成员,以便我可以在两个位置使用它.
我尝试过以下方法:
this.clazz = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
Run Code Online (Sandbox Code Playgroud)
但是getClass().getGenericSuperclass()返回一个无法强制转换为ParameterizedType的对象.我不能使用任何第三方反射库,我需要坚持Jdk内部的标准机制.
实际上,您非常接近实际的解决方案...您的代码的第一个版本非常接近您所需要的:
从:
public Context(final String resource, final Class<?> clazz) {
//...
}
Run Code Online (Sandbox Code Playgroud)
到:
public Context(final String resource, final Class<T> clazz) {
// ...
}
Run Code Online (Sandbox Code Playgroud)
一个?
改变T
就可以了。
归档时间: |
|
查看次数: |
76 次 |
最近记录: |