I'm trying to create an Interface with Generics which allows me to get the type of object in the generics but no matter what I try there's a syntax error. I've tried the following 3 methods.
All of the following code is and MUST be inside an interface with the generics <T extends Bar>
and I would rather the method getType()
be default
but it doesn't have to be.
public interface Foo<T extends Bar> {
public default Class<T> getType1() {
return T.class;
}
public default T getType2() {
return T;
}
public default T getType3() {
return new T();
}
}
1st method gives Error: Cannot select from a type variable
2nd method gives Error: Expression Expected
3rd method gives Error: Type parameter 'T' cannot be instantiated directly.
So if I had two classes that extend Bar
, let's just call them BarA
and BarB
, how can I make a method to figure out if the generic type is BarA
or BarB
?
T
during runtime. Generics is a strictly compile-time feature. – Ordous Jan 29 at 21:50getClass
on it. – Doval Jan 29 at 21:52T
of an object that implements the Foo class isinstanceof BarA
orinstanceof BarB
. – Gamefreak0 Jan 29 at 21:59