Home > Java > javaTutorial > 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

王林
Release: 2020-02-04 15:15:22
Original
4496 people have browsed it

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(); //得到泛型类型
Copy after login

Free learning video sharing: java video tutorial

Example: Obtaining the generic type in the List 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());
                }
            }
        }
    }
    
}
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template