2

Possible Duplicate:
Java reflection: Get concrete type of implemented generic interface

Say I have an interface:

public interface Monitor<T extends com.google.protobuf.Message>{
      public void checkMessage(T message)
}

and a concrete implementation:

public class MyMonitor implements Monitor<GeneratedMessage>{
      @Override
      public void checkMessage(GeneratedMessage message){
         //do something
      }
}

I want to write a utility method that I can pass MyMonitor to that will return GeneratedMessage.class. Is there any way to do this? I have seen a couple of blogs that are sort of related to this, but most of them are related to extended classes.

Also, if it is possible, can I declare Monitor<GeneratedMessage> monitor = new MyMonitor(); and pass monitor to the same method, and get GeneratedMessage back?

Community
  • 1
  • 1
CaTalyst.X
  • 1,645
  • 13
  • 16
  • 2
    This looks helpful: http://stackoverflow.com/questions/557663/retrieving-type-parameters-from-an-instance-of-a-generic-base-interface?rq=1: `MyMonitor.class.getGenericInterfaces()[0].getActualTypeArguments()` – Thilo Jul 13 '12 at 06:05
  • 2
    Generic types are meant to be only a compile-time check, so there's no easy/obvious way (if it's possible at all) to write the utility method you want. Maybe you can do it using reflection? Either way, it sounds like you have a bigger design flaw that should be fixed. – Mansoor Siddiqui Jul 13 '12 at 06:05
  • Thilo's suggestion works great: http://ideone.com/5fOjp – Ray Toal Jul 13 '12 at 06:22

0 Answers0