Consider the following code:
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);
I am trying to replace it with a generalized version of the Context class:
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();
Thus, I do not pass .class as a parameter to the constructor, and the unmarshall method automatically returns the returned object.
I need to know the class T to go to the newInstance () method and call the cast () method. those. T.class or T.getClass ().
In my example, I am trying to initialize the clazz member during the constructor so that I can use it in both places.
I tried the following:
this.clazz = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
However, getClass (). getGenericSuperclass () returns an object that cannot be passed to ParameterizedType. I cannot use third-party reflection libraries, I need to stick to the standard mechanisms inside Jdk.
source share