0

I have encountered the following scenario and I cannot find a simple solution.

#1

public class Foo<T> {
    @Override
    public T bar() {
        // access T.class
    }
}

Java Generics always want the Generic type to be of type class. So it is natural to expect to access the class type. Why it doesn't work that way?

#2

public class Foo<T> {
    @Override
    public T bar(Class C) {
        // automatically infer T to be of type `C`
    }
}

Is this possible in some way?

Elegant workarounds are welcome.

ryanafrish7
  • 3,222
  • 5
  • 20
  • 35
  • Iirc, Generic types "decay" to Object at runtime ("type erasure"?), so this isn't possible. – Carcigenicate Aug 20 '17 at 13:22
  • 1
    Not clear what you are asking, but for #2 you may want to say `public T bar(T c)` (or maybe `public T bar(Class extends T> c)` ) – Thilo Aug 20 '17 at 13:22
  • for #1, that is not possible (unless you have the constructor manually store a reference to `Class` ) due to type erasure. See https://stackoverflow.com/a/3437930/14955 – Thilo Aug 20 '17 at 13:23
  • 1
    [Please Go through following discussion, It may ](https://stackoverflow.com/questions/3403909/get-generic-type-of-class-at-runtime) – Onx Aug 20 '17 at 13:26

0 Answers0