2

N.B: If you find this duplicate then please read the bottom text first.

Code Overview

MyClass

public class MyClass<E> {
    E element;
}

ClassTwo

public class ClassTwo<E> {
    E[] collections;

    public ClassTwo(Class<E> c, int size) {
        collections = (E[]) Array.newInstance(c, size);
    }
}

Tester

public class Tester {
    public static void main(String[] args) {
        ClassTwo<MyClass<E>> two = new ClassTwo<MyClass<E>>(MyClass<E>.class, 10); // This causes an error
        ClassTwo<MyClass<E>> two2 = new ClassTwo<MyClass<E>>(MyClass.class, 10); // This also causes an error
    }
}

Question Description

For normal classes we can use ClassName.class to get the class of that class but how can we get the class of a generic type classes. For example:

MyClass.class gives Class<MyClass>

but why we cannot use MyClass<E>.class to get Class<MyClass<E>>?


Brief of Research

  1. Instantiating a generic class in Java
  2. How to get class of generic type in Spring
  3. Class Java, API 8
  4. Class Literals
  5. How to get a class instance of generics type T
  6. Incompatible types: Class cannot be converted to Class where CAP#1 is a fresh-type variable
  7. Java Generics Example Tutorial – Generic Method, Class, Interface

Clarification

After looking through the books and internet for a long time for getting my answer, I failed to found a solution matches my question or anything similar that I would use to solve the problem.

N.B: If you find my question is a duplicate of any other question please instead of down-voting refer me to the question. If advised I can delete my questing in case of duplicate question.

  • 1
    It is important to realize the limitations of generics: there is no difference between the classes of `new ArrayList()` and `new ArrayList()`: they are both simply `ArrayList`s, and the class for both is `ArrayList.class`. The `` bit is simply an instruction to the compiler to prevent you adding anything that's not a `String` (or null) to the list, and to assume that anything you get out can be cast to `String`. – Andy Turner Oct 22 '19 at 15:16
  • Oh. Thank you! So for that, since there cannot be any class like `Class>` then how can I solve the compile error that shows and get what I want. – Mohammed Julfikar Ali Mahbub Oct 22 '19 at 15:33

0 Answers0