Home >Backend Development >C++ >How to Determine Class Derivation with Generics in Java?
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>Solution:
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>This method will check the hierarchical structure (including generic) to determine the inheritance relationship. It provides a strong and flexible solution. Note that here we use directly, because we only need to determine whether the original type is matched without considering generic parameters. In the previous version, may return NULL or incorrect types in this situation, resulting in failure of judgment. The improved version is more reliable.
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!