1. Scenario 1: There is no inheritance relationship
public class A<T> {
Class<T> clazz;
public A(T... ts){
this. clazz = getTClass(ts);
}
static <T> Class<T> getTClass(@SuppressWarnings("unchecked") T... index) {
String name = "[Ljava.lang.Object;";
if (index! = null) // if the index argument is not empty
name = index.getClass () getName ();. // find the name of the corresponding type (array) according to the index
StringBuffer sbf = new StringBuffer();
for (int i = 2; i <name.length () - 1; i ++) // re-circulating placed inside sbf
sbf.append(name.charAt(i));
name = sbf.toString (); // Update the variable name
try {
return (Class <T>) Class.forName (name); // if error, class returns i.e. the presence of Class <?>
} catch (ClassNotFoundException e) {
System.err.println (e.getMessage ()); // if the error, class does not exist i.e., return null
}
return null;
}
}
2. Scenario 2: There is inheritance
public class DbAccess<T> implements IDbAccess<T> {
private Class<T> getTClass() {
Class<T> tClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass())
.getActualTypeArguments()[0];
Return Class;
}
}