4

How can I find the class of XOperation via Reflection API in Java?

public interface Operation<P extends Parameters> {
}

public class XParameters implements Parameters<XOperation> {
}

I'm trying to implement this method.

public <O extends Operation<P>, P extends Parameters> O getOperationByParametersClass(Class<P> parametersClass) {
    // TODO
}
barbara
  • 3,111
  • 6
  • 30
  • 58
  • So you want to pass e.g. `XParameters.class` to `getOperationByParametersClass` and it should return `XOperation.class`? Or...? – Radiodef May 13 '15 at 13:40
  • Yeap, that is what I want. – barbara May 13 '15 at 13:41
  • You probably want to look at http://stackoverflow.com/questions/1942644/get-generic-type-of-java-util-list and http://gafter.blogspot.com/2006/12/super-type-tokens.html (but comes with limitations) – Radiodef May 13 '15 at 13:42
  • 1
    In your example, there is no way to get the type of P by reflection. The information is simply not available at runtime ... due to type erasure. – Stephen C May 13 '15 at 14:10

1 Answers1

2

You can introduce a member in Parameters that will hold the Class of the type-parameter.

For example:

abstract class Parameters<T> {
    protected Class<T> type;
}

Then, in the getOperationByParametersClass() method, you should pass an instance of Parameters (including subclasses):

public <O extends Operation, P extends Parameters<O>> Class<O> 
             getOperationByParametersClass(P parametersInstance) {
    return parametersInstance.type;
}
Konstantin Yovkov
  • 62,134
  • 8
  • 100
  • 147