Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

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?

share|improve this question
5  
This is impossible due to erasure. You do not have the value of T during runtime. Generics is a strictly compile-time feature. –  Ordous Jan 29 at 21:50
    
What are you trying to do? If you wanted to get the class token of an object at runtime you'd call getClass on it. –  Doval Jan 29 at 21:52
    
@Doval elsewhere in the code I want to be able to figure out if the generic type T of an object that implements the Foo class is instanceof BarA or instanceof BarB. –  Gamefreak0 Jan 29 at 21:59
    
@Gamefreak0 Well, yes, naturally. But why do you want to do that? What problem are you trying to solve? There's probably a better way to do it. –  Doval Jan 29 at 22:01
    
@Ordous That's not strictly true. Not sure why, but subclasses that extend a generic class can get a hold of the type variable. See Super Type Tokens. –  Doval Jan 29 at 22:01

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.