Judging the inheritance relationship in the java generic environment
Question:
In the use of generic projects, you need to determine whether the given Type object is assigned a specified generic class. Due to the generic characteristics of the class, the use of
methods will fail.
IsSubclassOf
Example:
Consider the following class level structure:
The goal is to determine whether the Test class is derived from the genericClass.
<code class="language-java">public class GenericClass<T> implements GenericInterface<T> { } public class Test extends GenericClass<SomeType> { }</code>
Java provides a solution to this problem. First, we create a practical function:
Now, to check whether the test is derived from the Geneclass, please use the following code:
<code class="language-java">static boolean isSubclassOfRawGeneric(Type generic, Type toCheck) { while (toCheck != null && toCheck != Object.class) { Type cur = toCheck instanceof ParameterizedType ? ((ParameterizedType) toCheck).getRawType() : toCheck; if (generic == cur) { return true; } toCheck = toCheck.getSuperclass(); } return false; }</code>
The above is the detailed content of How to Determine Class Derivation with Generics in Java?. For more information, please follow other related articles on the PHP Chinese website!