Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return a class object "type" in java generics? [duplicate]

Imagine to have a java class

public class FixedClassOfStrings {

  List<String> myMember=new ArrayList<String>();

  // omissed all non relevant code...

  public Class getMyType() {
    return String.class;
  }
}

How can I make it paramteric, by using java generics?

My attempts fail:

public class GenericClass<T> {

  List<T> myMember=new ArrayList<T>();

  public Class getMyType() {
    return T.class; // this gives "Illegal class literal for the type parameter T"
  }
}

Also, how can I avoid warning: "Class is a raw type. References to generic type Class should be parameterized" in the FixedClassOsStrings? is it ok to declare:

  public Class<String> getMyType() {
    return String.class;
  }
  ...

And if it is ok, what shall I return using generics?

  public Class<T> getMyType() {
    return T.class; // this gives "Illegal class literal for the type parameter T"
  }
  ...

All hints will be appreciated!!!

like image 595
arzillo Avatar asked Oct 20 '22 09:10

arzillo


1 Answers

I would try something like this:

public Class<T> getMyType() {
    return /* some instance of T */.getClass();
}

Alternatively, an easy solution is passing the instance upon construction:

public class YourClass<T> {

    private final Class<T> type;

    public YourClass (/* arguments */, Class<T> type) {
        this.type = type;
    }

    public Class<T> getType() {
        return this.type;
    }

}
like image 62
Rogue Avatar answered Oct 23 '22 01:10

Rogue