myMe...">

How to return an object of class "type" in java generics?

Imagine you 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 this parametric 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 the warning: “A class is a raw type. References to the general type of Class must be parameterized” in FixedClassOsStrings? it's ok to declare:

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

And if everything is in order, what should I return using generics?

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

All tips will be appreciated!

+4
source share
1 answer

I would try something like this:

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

Alternatively, a simple solution passes the instance when building:

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;
    }

}
+2
source

Source: https://habr.com/ru/post/1538891/


All Articles