I'd like to find a hack to infer the actual generic instance of another instance's var in runtime, without:
- Changing my needed method signature (adding the helper parameter
Class<T>
, the obvious way) Having to
instanceof
all possible subtypes in a hardcoded wayMyInterface<? extends Number> myInterface = whateverReturnsWildcardDoubleInterface(); Class<?> type = inferInstanceType(myInterface); assert type == Double.class; /** This is the method that represents the code I am looking for with the conrete signature**/ public <T extends Number> Class<T> inferInstanceType(MyInterface<T> myInterface){ return T.class; //Concrete T (can or cannot be the very Number) }
Ideally, it should return Double when T is particular subtype Integer,Double.. and Number when T is Number
I checked reflection, several "TypeResolver"/"GenericResolver" libs (as the one in Spring or others in Github), but I cannot fin a way to hack it.
EDIT: I reached the conclusion that he only feasible way to do that would be some kind of very complex reflection through the stack trace up to the acutal line that passes the type in the very instantiation
EDIT2: I know it's stupid... but I solved it by simply adding a T getT()
method to my interface, so I could return myInterface.getT().getClass()