3

I'd like to retrieve the actual class of the generic type that is found on an object's parametrized marker interface. Is this even possible?

The marker interface:

public interface MarkerInterface<T> {}

The method i'd like to have:

public class findClassForParametrizedMarkerInterface(MarkerInterface<T> markedObjectThatCouldExtendSomeRandomClass){

    //How to retrieve the class T, or it's name?

}

For those wishing to know why I would like to do this: I have multiple dto jpa entities for some heavy jpa entities. I'd like to create a generic service that retrieves the correct full entity spring data jpa repository for the supplied dto. The dto's have a marker interface that specifies as parametrized generic type the full entity class.

Mark
  • 590
  • 7
  • 17

1 Answers1

0

Edit: a good discussion can be found at Get generic type of class at runtime. The simplest solution is to pass a reference to the class at the time of instantiation of the object. Maintain a reference to this class to return when needed. This is due to Java not holding onto generics at runtime. The generic info is available in metadata if you want to use the verbose reflection api to retrieve it.

use getClass() on the object itself.

public final Class getClass() Returns the runtime class of this Object. The returned Class object is the object that is locked by static synchronized methods of the represented class. The actual result type is Class where |X| is the erasure of the static type of the expression on which getClass is called. For example, no cast is required in this code fragment:

Number n = 0; Class c = n.getClass();

Returns: The Class object that represents the runtime class of this object. See Also: Literals, section 15.8.2 of The Java™ Language Specification.

http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#getClass()

Community
  • 1
  • 1
Andrew Gallasch
  • 2,432
  • 16
  • 24