0

I have a list of class types T and the following method that is called for the the class types:

<T extends PersistentEntity> void subscribe(Class<T> clazz, HBaseStreamFactory factory) {
    final DisposablePublisher<Tuple.Tuple2<T,T>> publisher 
        = new DisposablePublisher<>(factory.createPublisher(?));
}

The method createPublisher() should receive the class type of Tuple.Tuple2< T,T> instead of ?, how can I obtain it from knowing the clazz?

Turing85
  • 18,217
  • 7
  • 33
  • 58
Htag Tudy
  • 3
  • 2
  • 4
    You can't. `T` gets erased when compiling. This is called [Type Erasure](https://docs.oracle.com/javase/tutorial/java/generics/erasure.html). – Brian Jun 29 '15 at 07:35
  • 2
    you can get Tuple.Tuple2 type via Tuple.Tuple2.class . You cannot get the type of T because of type erasure. – Ataww Jun 29 '15 at 07:39
  • You can pass the type explicitly to the method `createPublisher`, can't you? In this way the the signature of the method will become the following: `createPublisher(Class clazz)`. – riccardo.cardin Jun 29 '15 at 07:39
  • possible duplicate of [how to get class instance of generics type T](http://stackoverflow.com/questions/3437897/how-to-get-class-instance-of-generics-type-t) – riccardo.cardin Jun 29 '15 at 07:42

1 Answers1

0

You can use Tuple.Tuple2.class, which is the class object representing the Tuple.Tuple2 class at runtime. (There are no generics at runtime anyway. There is just one class object for each class.) This expression has type Class<Tuple.Tuple2>. If you really want something of type Class<Tuple.Tuple<T,T>> to satisfy the compiler, you can do some unsafe casts:

factory.createPublisher((Class<Tuple.Tuple<T,T>>)(Class<?>)Tuple.Tuple2.class)

(or you can cast the result of createPublisher() accordingly; I don't have the method signatures so I can't predict how that would be written)

newacct
  • 119,665
  • 29
  • 163
  • 224