How do I get the `.class` attribute from a generic type parameter?

前端 未结 3 1968
星月不相逢
星月不相逢 2021-02-03 16:44

The accepted answer to this question describes how to create an instance of T in the Generic class. This involves passing in a Class<

3条回答
  •  悲&欢浪女
    2021-02-03 17:11

    W may not be available due to type erasure. You should require that a Class is passed into the method. You get a class object and its generic ensures that only W and no subclass is passed in, due to covariance.

    public InputField(String labelText, Class cls)
    {
        super(new String[] {labelText}, cls);
    }
    

    will take W.class but not WSubtype.class.

提交回复
热议问题