Home  >  Article  >  Java  >  Java determines whether a class is a subclass or parent class of a certain class

Java determines whether a class is a subclass or parent class of a certain class

王林
王林Original
2020-02-04 15:15:224484browse

Java determines whether a class is a subclass or parent class of a certain class

Class c = ArrayList.class;
c.isPrimitive(); //判断c是否为基本数据类型
c.isAssignableFrom(List.class);  //判断c是否是List类的子类或父类
c.getGenericType(); //得到泛型类型

Free learning video sharing: java video tutorial

Example: Obtaining the generic type in the List8742468051c85b06f0a0af9e3e506b5c collection through reflection

package com.zf.target;
 
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;
 
class T{
    List<A>  a;
    List<B>  b;
//    List l ;
    Map<Integer, String> map ;
    int c;
}
 
class A {}
class B{}
 
public class Test9{
 
    public static void main(String[] args) {
        Class tc = T.class;
        Field[] fields = tc.getDeclaredFields();
        for (Field f : fields) {
            Class fc = f.getType();
            if(fc.isPrimitive()){
                System.out.println("基本数据类型: " + f.getName() + "  " + fc.getName());
            }else{
                if(fc.isAssignableFrom(List.class)){ //判断是否为List
                    System.out.println("List类型:" + f.getName());
                    Type gt = f.getGenericType();    //得到泛型类型
                    ParameterizedType pt = (ParameterizedType)gt;
                    Class lll = (Class)pt.getActualTypeArguments()[0];
                    System.out.println("\t\t" + lll.getName());
                }
            }
        }
    }
    
}

Related article tutorial sharing: java introductory tutorial

The above is the detailed content of Java determines whether a class is a subclass or parent class of a certain class. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn