1

I have a problem when using generic types. IDE show me following error:

Cannot select from a type variable 

I think here problem with type erasure, but I think here exist some workaround...

My code:

class MyFactory {
  public Object getByClass(Class<?> clazz) {
     ..... 
  }
}


class<T> MyClass {
  private Object myObj = MyFactory.getByClass(T.class);  // HERE ERROR, `Cannot select from a type variable` 
  ...
}

How to solve this problem?

2
  • Because of type erasure, it's impossible to tell at runtime what T.class is supposed to refer to. Commented Feb 4, 2013 at 9:40
  • @millimoose The Type of T may not even be a Class. Commented Feb 4, 2013 at 9:41

1 Answer 1

3

Pass the Class object into the constructor.

private final Class<T> clazz;
private Object myObj
public MyClass(Class<T> clazz, MyFactory myFactory) {
    this.clazz = clazz;
    this.myObj = myFactory.getByClass(clazz);
}
Sign up to request clarification or add additional context in comments.

4 Comments

Shouldn't that read: this.myObj = myFactory.getByClass(clazz); Also, I don't think it's necessary to pass on the myFactory instance.
@JeroenWarmerdam Yup, fixed.
@JeroenWarmerdam (I mean I fixed the T.class to clazz. In the question getByClass is declared as an instance method. If it wasn't an instance method, then that would tend to suggest global state (a bad thing).)
I was reading the lower class in which the method is invoked statically. I see now that the upper class defines an instance method. I'll remove my example.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.